简体   繁体   中英

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!

This is because you are overwriting files while you are renaming.

Imagine the following file list after you deleted file 11:

1
10
12
2
3
4
5
...

If you now start renaming, the following happens:

1 -> 1
10 -> 2
12 -> 3
2 -> already overwritten by 10!

One solution: Sort your array using natsort($files) before renaming.

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); 
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM