如何更改客户端选择的图片的名称,并将其保存在具有不同名称的服务器中
I have the following code to upload to my server an image than the user sends through an input type=file.
My questions is: How can I change the name of the file?
Example: let's say than the user upload the following file: "mypicture.jpg" and I want to save it with the name of a variable I have stored, like $username where $username = John so even the user selected "mypicture.jpg" the file will be save in my directory (/var/www/html/images/) as John.jpg
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uploaddir = '/var/www/html/images/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.
";
} else {
echo "Possible file upload attack!
";
}
pg_close();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="3000000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
Thank you so much
我有以下代码上传到我的服务器的图像,而不是用户通过input type = file发送的图像。 / p>
我的问题是:如何更改文件名? p>
示例:假设用户上传以下文件:“mypicture。 jpg“我想用我已存储的变量的名称保存它,比如$ username其中$ username = John所以即使用户选择”mypicture.jpg“文件也会保存在我的目录中(/ var / www / html / images /)如John.jpg p>
&lt;?php
if($ _SERVER [“REQUEST_METHOD”] ==“POST”){
$ uploaddir ='/ var / www / html / images /';
$ uploadfile = $ uploaddir。 basename($ _ FILES ['userfile'] ['name']);
if(move_uploaded_file($ _ FILES ['userfile'] ['tmp_name'],$ uploadfile)){
echo“文件有效,是 已成功上传。
“;
}其他{
echo”可能的文件上传攻击!
“;
}
pg_close();
}
function test_input($ data){
$ data = trim($ data);
$ data = stripslashes($ data);
$ data = htmlspecialchars($ data);
return $ data;
}
?&gt;
&lt; form enctype =“multipart / form-data”action =“&lt;?php echo htmlspecialchars($ _ SERVER [”PHP_SELF“]);?&gt;” method =“POST”&gt;
&lt; input type =“hidden”name =“MAX_FILE_SIZE”value =“3000000”/&gt;
发送此文件:&lt; input name =“userfile”type =“file”/&gt;
&lt; input type =“submit”value =“发送文件”/&gt;
&lt; / form&gt;
code> pre>
非常感谢 p> \ n div>
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $username . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "/var/www/html/images/" . $newfilename);