[英]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.