[英]PHP File Upload (File Type) Filter
我对某些代码有疑问:
此代码有效:
if (!($uploadFile_type == "image/gif")) {
echo "Sorry, only GIF files are allowed.";
$uploadOk = 0;
}
现在,我想做倍数,所以我正在尝试:
if (($uploadFile_type != "image/gif") || ($uploadFile_type != "image/jpg") || ($uploadfile_type != "image/png")) {
echo "Sorry, only GIF/JPG or PNG files are allowed.";
}
问题是,每当我上传.jpg文件时,都会出现“抱歉,仅允许GIF / JPG或PNG文件”。
上面的代码有问题吗?
尝试这个..
$array = array('image/gif','image/jpg','image/png');
if(!in_array($uploadFile_type,$array)){
echo "Sorry, only GIF/JPG or PNG files are allowed.";
}
为什么不制作有效值数组,例如,
$valid_image_types = array('image/gif', 'image/jpeg', 'image/png');
然后检查此数组中的文件上传类型。
if (!in_array($uploadFile_type, $valid_image_types)) {
echo "Sorry, only GIF/JPG or PNG files are allowed.";
}
问题是您的状况:
if x or y
为真被评估,如果一个x
或y
是真实的。 在您的示例中,jpg肯定不等于png,为什么它始终会评估为true。
如何评估:
if(("image/jpeg" != "image/gif") || ("image/jpeg" != "image/jpeg") || ("image/jpeg" != "image/png"))
这使:
if(true || false || true)
这是:
if(true)
而是将其更改为:
if (!($uploadFile_type == "image/gif" || $uploadFile_type == "image/jpeg" || $uploadfile_type == "image/png"))
尝试这个
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$value = explode(".", $file_name);
$file_ext = strtolower(array_pop($value));
$expensions= array("jpeg","jpg","png","gif");
if(in_array($file_ext,$expensions)== false)
{
$errors="Extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"upload/".$file_name);
echo "Success";
}else
{
print_r($errors);
}
}
?>
这将只允许文件类型为image/png, image/jpg and image/png
$uploadFile_type = "image/png";
if ($uploadFile_type != "image/gif" and $uploadFile_type != "image/jpg" and $uploadFile_type != "image/png") {
echo "Sorry, only GIF/JPG or PNG files are allowed.";
}
您的代码中也有一个错字: $uploadfile_type != "image/png")
实际上:
$uploadFile_type != "image/png"
我有同样的问题,我尝试使用此代码,它现在可以正常工作
if ($uploadFile_type != "image/gif") {
if($uploadFile_type != "image/jpg") {
if($uploadfile_type != "image/png"){
echo "Sorry, only GIF/JPG or PNG files are allowed.";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.