Search code examples
phprenamesequential

PHP Renaming Sequentially deletes certain files


I am trying to have PHP rename a list of files in a directory sequentially (1.jpg, 2.jpg, etc.). About 20 files every time. Usually there is one number missing (like 13.jpg, so everything needs to be re-numbered.) That is what I need the script for. Below is what I have which works, except that every time images 2-9.jpg are deleted. So if there are 19 files in the folder, I run the script, and then there is 1.jpg and 10-18.jpg. Really weird? Is this fixable? Does it perhaps have to do with overwriting of the same filename? It's weird though that after 10.jpg it works fine...

$i=1;
foreach (array_filter(glob("../images/gallery/10/*") ,"is_file") as $f){
  rename($f, "../images/gallery/10/".$i.".jpg");
  $i++;
}

Thank you!


Solution

  • Thank you for all the answers! I was able to fix it -- the issue had to do with sorting. I found out that PHP saw the list sorted the wrong way like 1.jpg, 10.jpg, 11.jpg, etc. The following code fixed it though -- it works great now:

    <?php
    function getFiles(){
        $files=array();
        if($dir=opendir("../images/gallery/10/")){
            while($file=readdir($dir)){
                if($file!='.' && $file!='..' && $file!=basename(__FILE__)){
                    $files[]=$file;
                }   
            }
            closedir($dir);
        }
        natsort($files); //sort
        return $files;
    }
        $i=1;
         foreach(getFiles() as $f){
             rename("../images/gallery/10/".$f, "../images/gallery/10/".$i.".jpg");
      $i++;
      }
        ?>