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 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码