简体   繁体   English

PHP-重命名并上传文件(如果存在)

[英]PHP - Rename and upload a file if it exists

I have recently been learning to build an image gallery uploader in PHP. 我最近一直在学习用PHP构建图片库上传器。 I can't seem to work out how i actually rename my file before uploading it to my uploads folder. 在将文件上传到我的上载文件夹之前,我似乎无法弄清楚如何重命名文件。 Can anyone help me please? 谁能帮我吗?

Heres what i have so far. 这是我到目前为止所拥有的。

if(isset($_POST['submit'])) {
$allowedExts = array("gif", "jpeg", "jpg", "png","GIF","JPEG","JPG","PNG");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& in_array($extension, $allowedExts)) {

  if ($_FILES["file"]["error"] > 0) {
    echo "Invalid File Type";
  } else {

    $target = "../upload/";
    $name = addslashes($_FILES['file']["name"]);

    if(file_exists('../upload/' . $name)) {
        $explode = explode('.', $name); 
        $img = $explode[0];
        $ex = $explode[1];
        $i = 1;
        $new = $img . '_' . $i . '.' . $ex;

        while (file_exists('../upload/' . $new)) {
          $i++;
          $new = $img . '_' . $i . '.' . $ex;
        }

        // RENAME FILE HERE? 

    } 
      move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);
}

} else {
  echo "Error uploading image";
  die();
}

}

So right after my while loop is where i want to rename the file then use the move_uploaded_file()function to move it into my "upload" directory. 因此,在我的while循环之后,我想重命名文件,然后使用move_uploaded_file()函数将其移动到我的“上载”目录中。 Whats the best way i can achieve this? 我能做到这一点的最好方法是什么?

Thanks 谢谢

When you call move_file_upload you can simply give the new file its name as the second parameter, I understand the documentation doesn't make this clear but it works. 当您调用move_file_upload时,您可以简单地给新文件起第二个参数的名称,据我所知文档并不清楚,但可以使用。

move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);

So you would do something like 所以你会做类似的事情

move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"] . "Some random string to be added to the filename");

Or if you want to disregard the previous filename all together just remove it from your second parameter. 或者,如果您想一起忽略之前的文件名,只需将其从第二个参数中删除即可。

move_uploaded_file($_FILES["file"]["tmp_name"], $target. "new file name here");

Why not do that at the same time? 为什么不同时这样做呢?

You can rename it while moving it. 您可以在移动时重命名它。 Simply provide new file name as second parameter of move_uploaded_file() . 只需提供新文件名作为move_uploaded_file()第二个参数即可。

move_uploaded_file($_FILES["file"]["tmp_name"], $target . $new);

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

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