dtz46697 2013-09-09 19:36
浏览 24
已采纳

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

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.

  • 写回答

4条回答 默认 最新

  • dongxun3777 2013-09-09 19:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计