我正在使用此代码将照片上传到服务器:
<?php
$currentName = $_SESSION["uID"];
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
move_uploaded_file($_FILES["photo"]["tmp_name"], "img/profile_pictures/" . $filename);
// Add code to redirect back
header("location:".$_SERVER['HTTP_REFERER']);
exit;
} else{
echo "Error: There was a problem uploading your file. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
现在,当用户上传时,img/profile_pictures
中的文件名与所选文件的名称相同,但是我想将名称更改为$currentName
的值。我尝试将$filename
替换为$currentName
,但不起作用。我该怎么做?
我尝试更改$filename
,但扩展名消失了吗?:
move_uploaded_file($_FILES["photo"]["tmp_name"], "img/profile_pictures/" . $currentName);
答案 0 :(得分:0)
对于扩展,您可以使用以下内容:
move_uploaded_file($_FILES["photo"]["tmp_name"], "img/profile_pictures/" . $currentName.$ext);
$ _ FILES [“照片”] [“类型”] 是您要上传的文件的扩展名。
或者您设置一个完整的新名称,例如:
$newname = "newfile.png";
move_uploaded_file($_FILES["photo"]["tmp_name"], "img/profile_pictures/" . $newname);
答案 1 :(得分:0)
您错过了添加扩展名。如果使用!pip3 install requests
进行扩展,则会出现错误。所以:
$_FILES["photo"]["type"]
我建议使用图像名称:
if($_FILES['photo']['type'] == "image/jpeg"){
$ext= ".jpg";
}else{
$ext= ".png";
}
...
move_uploaded_file($_FILES["photo"]["tmp_name"], "img/profile_pictures/" . $currentName.$ext);