Search code examples
phprenamescandir

Renaming all files within different sub directories


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.


Solution

  • 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.