-2

I have the following array sent by ajax when echoed in php

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

and the following code to process the upload:

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

When I run the code I get the reply from php saying that file is neither an image nor a PDF although

$imageFileType gives me 'jpg'

A.K.
  • 141
  • 1
  • 2
  • 14
  • 2
    How can `$imageFileType` be equal to `jpg`, `png` and `jpeg` at __the same time__? __How__? – u_mulder Nov 21 '19 at 09:15
  • `pathinfo` get file extension from the file name. Which is not reliable. You can name a mp4 file to a jpg which will mislead `pathinfo`. Refer to this [answer](https://stackoverflow.com/a/57425890/6521116) for more detail. – LF00 Nov 21 '19 at 09:20

1 Answers1

3

You confused the && and || operator.

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

Can never be true, because the $imageFileType can never be those values all at the same time. Instead make it like

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

Or, personally I find this more pretty:

$allowedTypes = array("jpg","png","jpeg","gif");
if (! in_array($imageFileType, $allowedTypes)){ 
    //not allowed
}else{
    //allowed
}
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62