6

I need help. I want to rename all files to lower case within a directory recursively. I have a code to test but it only rename within that folder not recursively. How can I make it to do it recursively.

This is the code I use

<?php
 $directory="/data";
 $files = scandir($directory);
 foreach($files as $key=>$name){
    $oldName = $name;
    $newName = strtolower($name);
    rename("$directory/$oldName","$directory/$newName");
  }
?>
rkevx21
  • 2,441
  • 5
  • 19
  • 40
  • *nix or windows? often the os is better for this: http://stackoverflow.com/questions/152514/how-to-rename-all-folders-and-files-to-lowercase-on-linux –  Aug 24 '15 at 01:33
  • @Dagon a php code, that can be use in windows and ubuntu. – rkevx21 Aug 24 '15 at 01:36

2 Answers2

17

You can use the SPL's RecursiveDirectoryIterator for that.

<?php
$path = realpath('your/path/here');

$di = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach($di as $name => $fio) {
    $newname = $fio->getPath() . DIRECTORY_SEPARATOR . strtolower( $fio->getFilename() );
    echo $newname, "\r\n";
    //rename($name, $newname); - first check the output, then remove the comment...
}
VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • @VolkerK: Will this method also change case of the directory name? – l'L'l Aug 24 '15 at 02:12
  • No, it will not change the name of the directories. Because of `RecursiveIteratorIterator::LEAVES_ONLY` (and SKIP_DOTS) only files but not directories will be handled. If you want to rename the directories as well ...I guess `CHILD_FIRST` instead of `LEAVES_ONLY` will do the trick. – VolkerK Aug 24 '15 at 02:16
  • Just to mention, FileSystemIterator requires PHP >= 5.3.0 – AllisonC Apr 18 '17 at 14:01
0

This code works perfectly for me.

<?php
$dir= "path/";

    if($handle=opendir($dir)) {
        while($fileName=readdir($handle)){
            if(strlen($fileName)<100)  // 
            continue;
            $new_fn=strtolower($fn);
            rename($dir.$fileName,$dir.$new_fn);
        }
    }
?>
cihankaba
  • 7
  • 6