简体   繁体   English

PHP重命名文件(如果存在)

[英]PHP Rename file if exists

I've been working with image uploading and am wondering why this isn't working correctly? 我一直在进行图像上传,并且想知道为什么它不能正常工作? It doesn't move/upload the file with the new name if it already exists. 如果新名称已经存在,它不会移动/上传新名称的文件。

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.";
     }
}

You've included the folder path in $loc , then you attempt to move a file to userpics/$loc , which is probably incorrect. 您已经在$loc包含了文件夹路径,然后尝试将文件移动到userpics/$loc ,这可能是不正确的。 See the comments: 查看评论:

$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 {
    // ...

As a general debugging tip, always check a function's return value to see if it was successful. 作为一般的调试技巧,请始终检查函数的返回值以查看其是否成功。 Secondly, display the function's input values if it's failing. 其次,如果功能失败,则显示该功能的输入值。 It will make debugging things a lot easier. 这将使调试变得容易得多。

Try this: 尝试这个:

$fullpath = 'images/1086_002.jpg';
$additional = '1';

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

Thanks to here: Clickie!! 感谢这里: Clickie!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM