0

我想知道是否有人可以帮助我解决这个问题。我希望能够使用 PHP 将图片上传到用户主管,但我希望它将默认名称更改为 avatar.whatever。这是我到目前为止的代码,只是稍微修改了 w3schools 版本:

<?php
session_start();

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

    $home_dir = "users/" . $_SESSION["user"] . "/";

    if (file_exists($home_dir . $_FILES["avatar"]["name"]))
      {
      echo $_FILES["avatar"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["avatar"]["tmp_name"],$home_dir . $_FILES["avatar"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["avatar"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

表单部分效果很好,我会摆脱 if 语句检查文件是否已经存在并且输出不那么多,但有人可以帮我弄清楚如何设置预定义的文件名。用户将能够选择一个图片文件,然后将其上传到他们的目录。谢谢

4

2 回答 2

0

该行:

move_uploaded_file($_FILES["avatar"]["tmp_name"],$home_dir . $_FILES["avatar"]["name"]);

将使用第二个参数重命名文件:

move_uploaded_file($_FILES["avatar"]["tmp_name"],"/path/to/image_predefined_name.jpg");

将使用名称 image_predefined_name.jpg 保存它。

于 2013-06-10T17:23:11.553 回答
0

move_uploaded_files()函数(在代码的最后)接受两个参数:文件的临时位置和名称,以及所需的位置和名称。目前,您正在这样做:

 move_uploaded_file($_FILES["avatar"]["tmp_name"],$home_dir . $_FILES["avatar"]["name"]);
 echo "Stored in: " . "upload/" . $_FILES["avatar"]["name"];

其中存储文件的名称$_FILES["avatar"]["name"](用户的文件名)。只需将其替换为您想要的名称:$home_dir . "the name i want.whatever".

于 2013-06-10T17:24:38.340 回答