Question

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!

Was it helpful?

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top