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 multip开发者_如何学编程le 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);
?>
精彩评论