PHP重命名删除了一些文件?

I have the following photos:

product-1.jpg
product-2.jpg
product-3.jpg
product-4.jpg

I have the following request (came from jQuery's sortable):

action=save&photos=photo[]=4&photo[]=2&photo[]=3&photo[]=1

I've tried this:

<?php
if($_POST) {
    if($_POST['action'] == 'save') {
        parse_str($_POST['photos'], $photos);

        $id_new = 1;

        foreach($photos['photo'] as $id) {
            rename(dirname(__FILE__) . '/product-' . $id . '.jpg', dirname(__FILE__) . '/product-' . $id_new . '.jpg');

            $id_new++;
        }
    }
}
?>

But rename deletes some of the photos.

You have photos ids 4, 3, 2, 1 and you are renaming the files in the reverse order so:

  1. if you rename 4 to 1 then 1 is overwritten and 4 disappear
  2. if you rename 3 to 2 then 2 is overwritten and 3 disappear

That's why you remain with less files.

As @MVG1984 suggested in a comment you can rename those files into another folder like:

$path = dirname(__FILE__);
$tmpPath = $path . '/tmp';

mkdir($tmpPath);

$id_new = 1;
foreach($photos['photo'] as $id) {
    rename($path . '/product-' . $id . '.jpg', $tmpPath . '/product-' . $id_new . '.jpg');
    $id_new++;
}

for ($i = 1; $i < $id_new; $i++) {
    rename($tmpPath . '/product-' . $i . '.jpg', $path . '/product-' . $i . '.jpg');
}

rmdir($tmpPath);