且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将上传的文件保存到目录之前重命名?

更新时间:2023-09-05 13:28:28

您可以通过更改 move_uploaded_file 的第二个参数中的文件名来简单地更改文件的名称。


$ b

而不是

  move_uploaded_file($ _ FILES [file] [tmp_name ],../img/imageDirectory/。$ _FILES [file] [name]); 

使用

  $ temp = explode(。,$ _FILES [file] [name]); 
$ newfilename = round(microtime(true))。 ''。端($温度);
move_uploaded_file($ _ FILES [file] [tmp_name],../img/imageDirectory/。$ newfilename);

更改为反映您的问题,将根据当前时间产生一个随机数,并附加从最初上传的文件。

Below is the code I used in order to upload files into a directory. It works fine. My main question is:

move_uploaded_file() is the one that saves the uploaded file into the directory, and it is also my guess that move_uploaded_file() is the one that sets the name for it.

How could I change the name of my file to a random number?

I have tried to do so below:

      $allowedExts = array("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"))
      && ($_FILES["file"]["size"] < 100000)
      && in_array($extension, $allowedExts))
        {
        if ($_FILES["file"]["error"] > 0)
          {
          echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
          }
        else 
          {

            $fileName = $temp[0].".".$temp[1];
            $temp[0] = rand(0, 3000); //Set to random number
            $fileName;

          if (file_exists("../img/imageDirectory/" . $_FILES["file"]["name"]))
            {
            echo $_FILES["file"]["name"] . " already exists. ";
            }
          else
            {
            move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
            echo "Stored in: " . "../img/imageDirectory/" . $_FILES["file"]["name"];
            }
          }
        }
      else
        {
        echo "Invalid file";
        }

I tried changing variables such as the $_FILES["file"]["name"] and replacing it with the $fileName; variable so that the new name can be stored.

You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

Instead of

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);

Use

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.