PHP: File Download not checking the file type

advertisements

I am trying to upload an image file.

I receive the file name and OK and there are no errors, but for some reason when it reaches my file type if/else statement:

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

it will alsways say the file type is wrong. Ive tried with a few different file types of various sizes to no avail.

My full code is:

  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

  }

The line echo "<br />FILE TYPE: " . $filetype; shows I am uploading the correct file type (eg: FILE TYPE: image/png), just the if statement doesnt react...

Would anyone know why this is occurring?


use && not ||

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

its better to use PHP File Info also change your logic to:

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