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 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 游戏盾如何溯源服务器真实ip?
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥50 win10链接MySQL