我要做的是让它在用户上传文件时使用变量的值作为文件名,而不是实际文件的名称,然后将其保存为该名称。
因此,例如,如果变量是$variable = "50";
,我如何将文件保存为50.png
(或者将其上传到的任何扩展名)?
这是我的代码:
$variable = $_POST['id']; // taken from the form
$whitelist = 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"] < 2097152) && in_array($extension, $whitelist)) {
if($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "File name: " . $_FILES["file"][$user_id];
if(file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "Invalid file";
}
请帮忙。
答案 0 :(得分:0)
在你的行上
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
更改文件名。
$filenameAltered = '50.png';
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $filenameAltered);
答案 1 :(得分:0)
您可以使用其他变量或juste覆盖现有值。在文件顶部添加此行:
$_FILES["file"]["name"]='50.png';
答案 2 :(得分:0)
$variable = $_POST['id']; // taken from the form
$whitelist = 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"] < 2097152) && in_array($extension, $whitelist)) {
if($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "File name: " . $_FILES["file"][$user_id];
**$name2= $variable.".".$extension;**
if(file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
**move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $name2);**
echo "Stored in: " . "upload/" . $name2;
}
}
} else {
echo "Invalid file";
}