上传图像,符合要求但失败了

时间:2013-08-25 15:58:06

标签: php image upload

if(isset($_FILES['avatar']) && !empty($_FILES['avatar']['name'])){              
    if($_FILES['avatar']['type'] != "image/gif" || $_FILES['avatar']['type'] != "image/jpeg" || $_FILES['avatar']['type'] != "image/jpg" || $_FILES['avatar']['type'] != "image/pjpeg" || $_FILES['avatar']['type'] != "image/x-png" || $_FILES['avatar']['type'] != "image/png"){
        $errors[] = 'File does not have the right mime type.';
        $errors[] = '(This avatar has the mime type '. $_FILES['avatar']['type'] .')';
    }

    if($_FILES['avatar']['size'] > 40960){
        $errors[] = 'File is too large, max 40 kb.';
        $errors[] = 'This is '. $_FILES['avatar']['size'];
    }
}

再次问好stackoverflow!

我让我的用户在注册时决定是否要立即上传他们的头像,或者稍后再进行。

我目前正在尝试上传800b gif文件。但是在上传时,我得到的错误是该文件与允许的mime类型不匹配。我该怎么办?

1 个答案:

答案 0 :(得分:1)

||替换为&&

考虑一下,||表示or。如果type不是“image / gif”或者type不是“image / jpeg”,或者......其中一个是真的,你将输入if。例如,如果type是“image / gif”,那么它不是“image / jpeg”,你仍然会输入。

更优雅,替换为in_array。例如,

if(!in_array($type, ["image/gif", "image/jpeg"])) // and so on
    $errors[] = 'File does not have the right mime type.';