Search code examples
phpuploadfile-type

How can I only allow certain filetypes on upload in php?


I'm making a page where the user upload a file. I want an if statement to create an $error variable if the file type is anything other jpg, gif, and pdf.

Here's my code:

$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype

if(/*$file_type is anything other than jpg, gif, or pdf*/) {
  $error_message = 'Only jpg, gif, and pdf files are allowed.';
  $error = 'yes';
}

I'm having difficulty structuring the if statement. How would I say that?


Solution

  • Put the allowed types in an array and use in_array().

    $file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype
    
    $allowed = array("image/jpeg", "image/gif", "application/pdf");
    if(!in_array($file_type, $allowed)) {
      $error_message = 'Only jpg, gif, and pdf files are allowed.';
      $error = 'yes';
    }