我正在尝试嵌入文件上传器但是它显示pdf和其他应用程序文件的无效错误,在我使用的代码之后,任何人都可以帮助我找出错误,为什么它显示无效消息。提前谢谢。
<?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"]["type"] == "application/pdf"))
&& ($_FILES["file"]["size"] < 50000)
&& 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";
}
?>
答案 0 :(得分:2)
第1行只允许.gif
,.jpeg
,.jpg
,.png
:
$allowedExts = array("gif", "jpeg", "jpg", "png" );
如果您上传PDF,当然会提示Invalid file
答案 1 :(得分:0)
在你的
中 $allowedExts = array("gif", "jpeg", "jpg", "png" )
不包含“pdf”,请添加允许的扩展名“$ allowedExts”,如
$allowedExts = array("gif", "jpeg", "jpg", "png","pdf","php" );
答案 2 :(得分:0)
请尝试以下方法:
使用:$allowedExts = array("gif", "jpeg", "jpg", "png","pdf");
代替:$allowedExts = array("gif", "jpeg", "jpg", "png" );
为了将来,请记住添加您想要允许的扩展程序。
我希望这会有所帮助。
答案 3 :(得分:0)
已经指出了明显的错误。
除此之外,如果您将代码重构并重新格式化为
$allowedExts = Array("gif", "jpeg", "jpg", "png" );
$allowedContentTypes = Array("application/pdf", "image/png", "image/jpeg", "image/jpg", "image/gif");
$fileSizeLimit = 50000;
function getExtension($file)
{
return end(explode(".", $file["name"]));
}
function hasAllowedContentType($file)
{
return in_array($file['type'], $allowedContentTypes);
}
function isWithinSizeLimits($file)
{
return $file['size'] < $fileSizeLimit;
}
function hasAllowedExtension($file)
{
$extension = getExtension($file['name');
return in_array($extension, $allowedExts);
}
function alreadyExists($path)
{
return file_exists($path);
}
$file = $_FILES["file"];
$targetPath = "upload/" . $file["name"];
$tempPath = $file["tmp_name"];
if (!hasAllowedContentType($file)
|| !isWithinSizeLimits($file)
|| !hasAllowedExtension($file))
{
echo "Invalid file";
}
else if ($file["error"] > 0)
{
printf("Return Code: %s<br>", $file["error"]);
}
else
{
printf("Upload: %s<br>", $file["name"]);
printf("Type: %s<br>", $file["type"]);
printf("Size: %d kB<br>", ($file["size"] / 1024));
printf("Temp file: %s<br>", $tempPath);
if (alreadyExists($targetPath))
{
printf("%s already exists.", $file["name"]);
}
else
{
move_uploaded_file($tempPath, $targetPath);
printf("Stored in: %s", $targetPath);
}
}
理解和维护已经容易得多了。