PHP:文件上传未验证文件类型

时间:2013-02-14 05:46:55

标签: php file-upload if-statement verification file-type

我正在尝试上传图片文件。

我收到文件名并且没有错误,但出于某种原因,当它到达我的文件类型if / else语句时:

if($filetype != 'image/jpeg' || $filetype != 'image/jpg' || $filetype != 'image/png' || $filetype != 'image/gif') {
//ERROR - NOT CORRECT TYPE
}
else {
//CORRECT FILE TYPE..CONTINUE
}

它会说文件类型错误。我试过几种不同大小的文件类型无济于事。

我的完整代码是:

  if(!$_FILES['photo'.$i]['error'])
  {
   echo "<br />NO ERRORS FOUND";

      //FILE TYPE CHECKER
      $filetype = $_FILES['photo'.$i]['type'];
      echo "<br />FILE TYPE: " . $filetype;

      if($filetype != 'image/jpeg' || $filetype != 'image/jpg' || $filetype != 'image/png' || $filetype != 'image/gif') {
        $valid_file = false;
        $message = 'Wrong file type. Please only upload jpg, jpeg, gif or png files';
      }//END FILE CHECKER IF

      else {
        echo "<br />FILE TYPE OK";
      }//END FILE TYPE CHECK ELSE

  }

echo "<br />FILE TYPE: " . $filetype;显示我正在上传正确的文件类型(例如:FILE TYPE:image / png),只是if语句没有反应......

有谁知道为什么会这样?

2 个答案:

答案 0 :(得分:1)

使用&amp;&amp;不是||

if($filetype != 'image/jpeg' && $filetype != 'image/jpg' && $filetype != 'image/png' && $filetype != 'image/gif') {
//ERROR - NOT CORRECT TYPE
}

最好使用PHP File Info也将您的逻辑更改为:

$allowed_mimes = array('image/jpeg', 'image/jpg');
if(!in_array($filetype, $allowed_mimes)){
 //eeror
}

答案 1 :(得分:0)

更改||和&amp;&amp; - 如果是||它永远都是真的。

if($filetype != 'image/jpeg' && $filetype != 'image/jpg' && $filetype != 'image/png' && $filetype != 'image/gif') {
相关问题