正如标题所说,我希望在用户上传文件后将用户重定向回主页,到目前为止,所有这些代码都显示一个包含相关信息的页面(文件名,文件大小等)。 )我想将它们重定向到自定义成功页面。
HTML:
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_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
{
"Upload: " . $_FILES["file"]["name"] . "<br>";
"Type: " . $_FILES["file"]["type"] . "<br>";
"Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
"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"]);
header('Location: success.html');
}
}
}
else
{
echo "Invalid file";
}
?>
答案 0 :(得分:1)
假设您的成功页面是'success.html',您可以使用:
header('Location: success.html');
您需要删除所有回声线,因为它会导致“已发送标题”异常。
从工作流程的角度来看,回显屏幕然后重定向也没有任何意义。
删除以下行:
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>";
此外,您可以将所有文件类型存储在数组中,并使代码更清晰:
$allowedTypes = array("image/gif",..,..,"image/png");
然后使用
in_array($_FILES["file"]["type"], $allowedTypes);
完整代码:
<?
$allowedExts = array("gif", "jpeg", "jpg", "png");
$allowedTypes = array("image/gif",'..','..',"image/png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((in_array($_FILES["file"]["type"], $allowedTypes))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
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"]);
header('Location: success.html');
}
}
}
else
{
echo "Invalid file";
}
?>
希望这有帮助!