duanhuan1147 2017-07-21 06:26
浏览 52
已采纳

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.

  • 写回答

1条回答 默认 最新

  • dqy006150 2017-07-21 06:38
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存