【问题标题】:PHP Rename file if existsPHP重命名文件(如果存在)
【发布时间】:2014-08-09 04:11:29
【问题描述】:

我一直在处理图片上传问题,想知道为什么这不能正常工作?如果文件已经存在,它不会移动/上传具有新名称的文件。

if(isset($_REQUEST['submit'])){
     $filename=  $_FILES["imgfile"]["name"];
        if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png")  || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)){
    $loc = "userpics/$filename";
    if(file_exists($loc)){
        $increment = 0;
        list($name, $ext) = explode('.', $loc);
        while(file_exists($loc)) {
            $increment++;
            $loc = $name. $increment . '.' . $ext;
            $filename = $name. $increment . '.' . $ext;
        }
      move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");

    }
    else{
      move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$filename");

    }
     }
     else{
    echo "invalid file.";
     }
}

【问题讨论】:

  • 你应该使用while而不是if(file_exists){...}
  • 也许你应该检查move_uploaded_file的返回值?看起来如果文件存在,你最终将它移动到userpics/userprics/blahblah
  • @Fred-ii-: 那只会重命名文件一次,不会检查重命名的文件是否存在。
  • @TheBlueDog 好点;我的立场是正确的。
  • 你应该检查文件扩展名,否则可能会上传.php文件或其他恶意文件。

标签: php file if-statement rename exists


【解决方案1】:

您已在$loc 中包含文件夹路径,然后您尝试将文件移动到userpics/$loc,这可能不正确。查看 cmets:

$filename = "example.jpg";
$loc = "userpics/$filename";
if(file_exists($loc)){
    $increment = 0;
    list($name, $ext) = explode('.', $loc);
    while(file_exists($loc)) {
        $increment++;
        // $loc is now "userpics/example1.jpg"
        $loc = $name. $increment . '.' . $ext;
        $filename = $name. $increment . '.' . $ext;
    }

    // Now you're trying to move the uploaded file to "userpics/$loc"
    //   which expands to "userpics/userpics/example1.jpg"
    move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
} else {
    // ...

作为一般调试提示,总是检查函数的返回值以查看它是否成功。其次,如果函数失败,则显示函数的输入值。这将使调试变得更加容易。

【讨论】:

    【解决方案2】:

    试试这个:

    $fullpath = 'images/1086_002.jpg';
    $additional = '1';
    
    while (file_exists($fullpath)) {
        $info = pathinfo($fullpath);
        $fullpath = $info['dirname'] . '/'
                  . $info['filename'] . $additional
                  . '.' . $info['extension'];
    }
    

    感谢这里:Clickie!!

    【讨论】:

      猜你喜欢
      • 2015-03-18
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 2012-03-06
      • 2014-07-20
      • 2013-09-29
      相关资源
      最近更新 更多