1

I m trying to rename files to lowercase within a directory, however the problem I'm having is being able to scan the sub-directories for the files.

So in this case $app_dir is the main directory and the files I need to change exist within multiple sub-folders.

Heres my code so far:

$files = scandir($app_dir);
foreach($files as $key=>$name){
$oldName = $name;
$newName = strtolower($name);
rename("$app_dir/$oldName","$app_dir/$newName");
}

Thanks for your help.

Mauker
  • 11,237
  • 7
  • 58
  • 76
Dan Hayman
  • 25
  • 3
  • maybe useful? [PHP read sub-directories and loop through files how to?](http://stackoverflow.com/questions/2014474/php-read-sub-directories-and-loop-through-files-how-to) – Ryan Vincent Aug 21 '15 at 15:38

3 Answers3

1

If you are trying to lowercase all file names you can try this:

Using this filesystem:

Josh@laptop:~$ find josh
josh
josh/A
josh/B
josh/f1
josh/f2
josh/is
josh/is/awesome
josh/is/awesome/e
josh/is/awesome/t

Code:

<?php
$app_dir = 'josh';
$dir = new RecursiveDirectoryIterator($app_dir, FilesystemIterator::SKIP_DOTS);
$iter = new RecursiveIteratorIterator($dir);
foreach ($iter as $file) {
    if ($file != strtolower($file)) {
        rename($file, strtolower($file));
    }
}

Results:

Josh@laptop:~$ find josh
josh
josh/a
josh/b
josh/f1
josh/f2
josh/is
josh/is/awesome
josh/is/awesome/e
josh/is/awesome/t

This code does not take into account uppercase letters in directories but that exercise is up to you.

Josh J
  • 6,813
  • 3
  • 25
  • 47
0

You could do this with a recursive function.

function renameFiles($dir){
    $files = scandir($dir);
    foreach($files as $key=>$name){
        if($name == '..' || $name == '.') continue;
        if(is_dir("$dir/$name"))
            renameFiles("$dir/$name");
        else{
            $oldName = $name;
            $newName = strtolower($name);
            rename("$dir/$oldName", "$dir/$newName");
        }
    }
}

This basically loops through a directory, if something is a file it renames it, if something is a directory it runs itself on that directory.

TheGentleman
  • 2,324
  • 13
  • 17
0

Try like that

public function renameFiles($dir)
{
    $files = scandir($dir);
    foreach ($files as $key => $name) {
        if (is_dir("$dir/$name")) {
            if ($name == '.' || $name == '..') {
                continue;
            }
            $this->renameFiles("$dir/$name");
        } else {
            $oldName = $name;
            $newName = strtoupper($name);
            rename("$dir/$oldName", "$dir/$newName");
        }
    }
}
nyotsov
  • 93
  • 7