Search code examples
phprenameunlink

PHP numerically rename all files in directory


I have a script to upload files and name them numerically (say 1-15) and when I delete a file (say number 5) I want the files to be renamed 1-14. This works okay if I delete a file 9 and under, if I delete anything over 10 it erases multiple files. As far as I can tell the problem isn't with the deletion but the renaming

Here's the piece of script I'm having trouble with:

unlink($path.$img);

$files = natsort(glob("$path/*.jpg"));

$num = 1;

foreach($files as $file) {
  $new = 'photo' . $num . '.jpg'; 
  rename($file, dirname($file).'/'.$new);
  $num++;
}

Thanks!


Solution

  • working example from php.net

     <?php 
    $path = "E:\\SERVER\\sudhir\\songs"; 
    $dh = opendir($path); 
    $i=1; 
    while (($file = readdir($dh)) !== false) { 
        if($file != "." && $file != "..") { 
            echo "<br/>".substr($path."\\".$file, 0,-3)."_mysongs_mp3"; 
            rename($path."\\".$file, substr($path."\\".$file, 0,-3)."_mysongs_mp3"); 
            $i++; 
        } 
    } 
    closedir($dh); 
    ?>