我想知道是否有人可以帮助我解决这个问题。我希望能够使用 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 语句检查文件是否已经存在并且输出不那么多,但有人可以帮我弄清楚如何设置预定义的文件名。用户将能够选择一个图片文件,然后将其上传到他们的目录。谢谢