首页 > 解决方案 > PHP 无法识别文件上传扩展名

问题描述

在 php 中回显时,我有以下由 ajax 发送的数组

[file] => Array
    (  [name] => XXXX.jpg    [type] => image/jpeg   [tmp_name] => D:\xampp\tmp\phpC5F2.tmp
        [error] => 0    [size] => 25245     )

以及处理上传的以下代码:

if(isset($_FILES['file'])) {
 $natid = '9999';
 $target_dir = "../uploads/";
 $fname = $_FILES['file']['name'];
 $target_file = $target_dir . $natid .'/'. $fname;
 $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));            

  if($imageFileType == "jpg" && $imageFileType == "png" && $imageFileType == "jpeg" && $imageFileType == "gif") {
    $check = getimagesize($_FILES["file"]["tmp_name"]); 
        if($check !== false) {  //  !== not equal
            echo "File is an image - " . $check["mime"] . ".<br>";
        } else {
            echo "the file is not an image.";
        }
  } elseif ($imageFileType == "pdf"){
    echo "File is a PDF - " . $check["mime"] . ".<br>";
  } else {
    echo "Sorry, only PDF, JPG, JPEG, PNG & GIF files are allowed.";
  }
}

当我运行代码时,我得到了 php 的回复,虽然该文件既不是图像也不是 PDF

$imageFileType 给了我'jpg'

标签: phphtmlajaxpdf

解决方案


您混淆了&&and||运算符。

$imageFileType == "jpg" && $imageFileType == "png" && $imageFileType == "jpeg" && $imageFileType == "gif"

永远不可能是真的,因为 $imageFileType 永远不可能同时是这些值。而是让它像

$imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg" || $imageFileType == "gif"

或者,我个人觉得这个更漂亮:

$allowedTypes = array("jpg","png","jpeg","gif");
if (! in_array($imageFileType, $allowedTypes)){ 
    //not allowed
}else{
    //allowed
}

推荐阅读