PHP文件上传(文件类型)过滤器

时间:2014-10-15 11:13:49

标签: php

我遇到了一些代码问题:

此代码有效:

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文件。”

上面的代码有问题吗?

6 个答案:

答案 0 :(得分:2)

试试这个..

$array = array('image/gif','image/jpg','image/png');
if(!in_array($uploadFile_type,$array)){
    echo "Sorry, only GIF/JPG or PNG files are allowed.";
}

答案 1 :(得分:2)

为什么不制作有效值数组,例如

$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.";
}

答案 2 :(得分:1)

问题在于你的条件:

如果if x or yx中的一个为真,则

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"))

答案 3 :(得分:0)

试试这个

<?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);
    }
}
?>

答案 4 :(得分:0)

这只允许文件类型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"

Sandbox

答案 5 :(得分:-1)

我有同样的问题,我尝试使用此代码,它现在可以正常工作

 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.";
                }
             }
          }