1

我目前想使用 w3schools 图像上传代码,直到找到我不久前编写的代码。反正:

<?php
 $allowedExts = array("gif", "jpeg", "jpg", "png");
 $extension = end(explode(".", $_FILES["file"]["name"]));
 if ((($_FILES["file"]["type"] == "image/gif")
 || ($_FILES["file"]["type"] == "image/jpeg")
 || ($_FILES["file"]["type"] == "image/jpg")
 || ($_FILES["file"]["type"] == "image/png"))
 && ($_FILES["file"]["size"] < 20000)
 && in_array($extension, $allowedExts))
 {
 if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
 echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

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";
 }
?>

基本上我想要发生的是当用户上传文件时,它将文件名重命名为 $username 而不是原始名称,所以它只是 username.png 而不是我目前拥有的 username-38474.png

有什么帮助吗?

4

2 回答 2

8
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);

这行代码基本上将图像重命名为新位置: to "upload/".$_FILES["file"]["name"],因此将这一行替换为:

move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$username.".".$extension);
于 2013-04-17T20:19:01.553 回答
0

所以只需将不同的参数传递给move_uploaded_file

$extension = explode("/", $_FILES["file"]["type"]);  //Use proper mime type here, $_FILES contents can be faked by remote user
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $username.".".$extension[1]);
于 2013-04-17T20:18:45.027 回答