[英]PHP upload image script isn't working
<?
if(isset($_POST['upload'])) {
if(empty($_FILES['image'])) {
echo "<p class=\"error\">Please upload an image...</p>\n";
} else {
$file_name= $_FILES['image']['name']; // original name
$file_type = $_FILES['image']['type'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name']; // temporary location on server
$file_error = $_FILES['image']['error']; // reference to future error
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
if($file_ext != "jpeg" || "jpg" || "gif" || "png") {
echo "<p class=\"error\">Please upload an image that has the extension .jpg/jpeg, .gif, or .png.</p>\n";
} else {
if($file_size > (10000000)) {
echo "<p class=\"error\">Please upload an image that does not exceed the file size of 10MB.</p>\n";
} else {
if($file_error) {
echo "<p class=\"error\">Sorry, an unexpected error occurred: ".$file_error."</p>\n";
} else {
$f_rename = "pfp/".time().".png";
move_uploaded_file($file_tmp,$f_rename);
}
}
}
}
}
?>
<!doctype html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form action="upload_test_image.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="upload" value="Upload"/>
</form>
</body>
</html>
我无法上传任何图片,因为无法通过文件扩展名检查。 在撰写本文时,我还试图剖析问题是否在于扩展验证确实是问题所在(可能是因为它只是打印出我发布的错误声明,原因是它首先出现在... else语句)。 任何人都可以在该代码或此代码中帮助找到问题吗?
pathinfo()将需要文件的路径而不仅仅是文件名。 要扩展,您可以尝试以下操作:
$extension = preg_replace('@.+\.@', '', $_FILES['image']['name'])
另外,您可以检查$ _FILES ['image'] ['type'],因为其中可能包含您要查找的类型。 finfo可能也有帮助: http ://php.net/manual/en/function.finfo-file.php
我不认为您可以在PHP中执行这样的布尔条件。
怎么样,声明一个允许的扩展数组:
$extensions = array("jpeg", "jpg", "gif","png");
然后检查文件扩展名是否在数组中:
if(!in_array($file_ext, $extensions)) {
//Please upload an image that has the extension .jpg/jpeg, .gif, or .png.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.