如何在将上传的文件保存到目录之前重命名它? [英] How to rename uploaded file before saving it into a directory?
问题描述
下面是我用来将文件上传到目录的代码.它工作正常.我的主要问题是:
Below is the code I used in order to upload files into a directory. It works fine. My main question is:
move_uploaded_file() 是将上传的文件保存到目录中的那个,我也猜测 move_uploaded_file() 是为
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";
}
我尝试更改诸如 $_FILES["file"]["name"] 之类的变量并将其替换为 $fileName; 变量,以便新名称可以存储.
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.
推荐答案
您可以通过在 move_uploaded_file
的第二个参数中更改文件名来简单地更改文件名.
You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file
.
代替
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
使用
$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.
这篇关于如何在将上传的文件保存到目录之前重命名它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!