Validating Mime Type and Extension of File Uploads

Learn how to check the file extension and MIME type of the uploaded (or any) file in PHP.

Checking File Mime Type

 //$file = $_FILES['upload']['tmp_name'];
 $file  = 'uploads/image.png';
 $mtype = mime_content_type($file);
 echo $mtype; // image/png

Checking a file type by using the $_FILES['upload']['type'] is not a reliable way. It returns mime type based on the file extension, for example, if the file extension is png it returns ‘image/png’ and if the file extension is txt it returns ‘text/plain’.

In the above example, we are using the mime_content_type function to load the actual content type of a file (from the magic.mime file on your PHP server) regardless of its extension.

Example: Creating a function to validate file mime type

 // ... ...
 $file = $_FILES['upload']['tmp_name'];

 $error = isValidMimeType( $file ) ;
 if ($error === false)
  echo 'File is valid';
  echo $error;

 function isValidMimeType($file){
  $types = ['image/jpeg','image/gif','image/png'];
  $type  = mime_content_type($file);

  if ( in_array($type, $types) )
   return false;
  return 'Error: Only '. implode (', ', $types). ' are allowed';

Checking file extension

To determine if a file is potentially unsafe, you need to extract the filename extension. You can do that with the pathinfo() function:

 //$file = $_FILES['upload']['name'];
 $file = '/usr/etc/';
 $info = pathinfo($file);
 echo $info['extension']; // prints: php

/* Prints: Array
    [dirname] => /usr/etc
    [basename] =>
    [extension] => php
    [filename] =>

The PHP pathinfo() function returns information about a file path (including the file extension). By default it returns an associative array with the following keys:

  1. dirname: directory that contains the file
  2. basename: file name including extension
  3. extension: file extension
  4. filename: file name without extension

Example: Creating a function to restrict (or allow multiple) file extensions

 //$filename = $_FILES['upload']['name'];
 $filename = 'system.exe';
 $error = isValidExtension ($filename);
 if ($error === false)
  echo 'Valid file extension';
  echo $error;

 function isValidExtension($file) {
  $exts = ['gif', 'png', 'jpg'];
  $info = pathinfo($file);
  if (in_array($info['extension'], $exts))
   return false;
  return 'Error: Only '. implode (', ', $exts). ' are allowed';

The above code outputs “Error: Only gif, png, jpg are allowed” on the screen.

Processing Forms in PHP: