PHP: Check (validate) if the Uploaded File is an Image

Posted on September 24, 2008, under PHP 

In this tutorial I will show you how to create an image validator script. You can choose between 2 methods of validation: one that will verify if the file is actually an image, by checking the file’s mime-type, and the other one which checks the extension of the uploaded file.

Let’s start creating the configuration file:

config.php

<?php
/* 
1 = Check if the file uploaded is actually an image no matter what extension it has
2 = The uploaded files must have a specific image extension
*/

$validation_type = 1;

if($validation_type == 1)
{
	$mime = array('image/gif' => 'gif',
                  'image/jpeg' => 'jpeg',
                  'image/png' => 'png',
                  'application/x-shockwave-flash' => 'swf',
                  'image/psd' => 'psd',
                  'image/bmp' => 'bmp',
                  'image/tiff' => 'tiff',
                  'image/tiff' => 'tiff',
                  'image/jp2' => 'jp2',
                  'image/iff' => 'iff',
                  'image/vnd.wap.wbmp' => 'bmp',
                  'image/xbm' => 'xbm',
                  'image/vnd.microsoft.icon' => 'ico');
}
else if($validation_type == 2) // Second choice? Set the extensions
{
	$image_extensions_allowed = array('jpg', 'jpeg', 'png', 'gif','bmp');
}

$upload_image_to_folder = 'images/';
?>

Now let’s create the form that will help us to upload the file:

<form enctype="multipart/form-data" action="validate_image_upload.php" method="POST">
    
<!-- MAX_FILE_SIZE must be set before the input element -->
<input type="hidden" name="MAX_FILE_SIZE" value="2048000" />

<!-- The name from the $_FILES array is determined by the input name -->
Select an Image: <input name="image_file" type="file" /> 
<input type="submit" value="Upload" />

</form>

Our form will send the data to validate_image_upload.php. Here, the script will check the type of validation. If the file is validated the user will see a successful submission message and the file will be moved in the specified image folder. The uploaded file failed to pass the validation process? In this case, it will be deleted and the script will output an error message.

<?php
// Do not show notice errors
error_reporting (E_ALL ^ E_NOTICE);

if(!empty($_FILES)) // [START FILE UPLOADED]
{
include 'config.php';

$file = $_FILES['image_file'];

$file_name = $file['name'];

$error = ''; // Empty

// Get File Extension (if any)

$ext = strtolower(substr(strrchr($file_name, "."), 1));

Validation #1 – Check if the uploaded file is an image. This is done using the getimagesize() function:

array getimagesize ( string $filename [, array &$imageinfo] )

This function returns an array with specific information regarding the file. To return specific information such as width, height, mime type, channels, the file that is verified should be a valid image. If $file_info is empty, then the uploaded file is not an image.

We will detect the image’s mime type and we will use this information to add the correct extension to the file.

// Check for a correct extension. The image file hasn't an extension? Add one

   if($validation_type == 1)
   {
   $file_info = getimagesize($_FILES['image_file']['tmp_name']);

      if(empty($file_info)) // No Image?
      {
      $error .= "The uploaded file doesn't seem to be an image.";
      }
      else // An Image?
      {
      $file_mime = $file_info['mime'];

         if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
         {
         $extension = $ext;
         }
         else
         {
         $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
         }

         if(!$extension)
         {
         $extension = '';
         $file_name = str_replace('.', '', $file_name);
         }
	  }
   }

Validation #2 – Check the extension of the uploaded file

We’ll use in_array() to determine if the filename’s extension can be found in our list with extensions from config.php. If the extension is not on the list, an error message would be generated notifying the user that the uploaded file’s extension is not an accepted one.

   else if($validation_type == 2)
   {
	  if(!in_array($ext, $image_extensions_allowed))
	  {
	  $exts = implode(', ',$image_extensions_allowed);
	  $error .= "You must upload a file with one of the following extensions: ".$exts;
	  }

	  $extension = $ext;
   }

If no errors were found, copy the file to the specified folder ($upload_image_to_folder) and show a successful submission message to the user.


   if($error == "") // No errors were found?
   {
   $new_file_name = strtolower($file_name);
   $new_file_name = str_replace(' ', '-', $new_file_name);
   $new_file_name = substr($new_file_name, 0, -strlen($ext));
   $new_file_name .= $extension;
   
   // File Name
   $move_file = move_uploaded_file($file['tmp_name'], $upload_image_to_folder.$new_file_name);

   if($move_file)
	   {
	   $done = 'The image has been uploaded.';
	   }
   }
   else
   {
   @unlink($file['tmp_name']);
   }

   $file_uploaded = true;
} // [END FILE UPLOADED]
?>

Check the complete validate_image_upload.php file which has the HTML Form and the Validator:

validate_image_upload.php

<?php
// Do not show notice errors
error_reporting (E_ALL ^ E_NOTICE);

if(!empty($_FILES)) // [START FILE UPLOADED]
{
include 'config.php';

$file = $_FILES['image_file'];

$file_name = $file['name'];

$error = ''; // Empty

// Get File Extension (if any)

$ext = strtolower(substr(strrchr($file_name, "."), 1));

// Check for a correct extension. The image file hasn't an extension? Add one

   if($validation_type == 1)
   {
   $file_info = getimagesize($_FILES['image_file']['tmp_name']);

      if(empty($file_info)) // No Image?
      {
      $error .= "The uploaded file doesn't seem to be an image.";
      }
      else // An Image?
      {
      $file_mime = $file_info['mime'];

         if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
         {
         $extension = $ext;
         }
         else
         {
         $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
         }

         if(!$extension)
         {
         $extension = '';
         $file_name = str_replace('.', '', $file_name);
         }
	  }
   }
   else if($validation_type == 2)
   {
	  if(!in_array($ext, $image_extensions_allowed))
	  {
	  $exts = implode(', ',$image_extensions_allowed);
	  $error .= "You must upload a file with one of the following extensions: ".$exts;
	  }

	  $extension = $ext;
   }

   if($error == "") // No errors were found?
   {
   $new_file_name = strtolower($file_name);
   $new_file_name = str_replace(' ', '-', $new_file_name);
   $new_file_name = substr($new_file_name, 0, -strlen($ext));
   $new_file_name .= $extension;
   
   // File Name
   $move_file = move_uploaded_file($file['tmp_name'], $upload_image_to_folder.$new_file_name);

   if($move_file)
	   {
	   $done = 'The image has been uploaded.';
	   }
   }
   else
   {
   @unlink($file['tmp_name']);
   }

   $file_uploaded = true;
} // [END FILE UPLOADED]
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title>Validate Image on Upload @ BitRepository.com</title>
  <meta name="Author" content="BitRepository.com">

  <meta name="Keywords" content="validate, image, upload, post, files">
  <meta name="Description" content="How to check if an uploaded file is an image">
 </head>

 <body>

<center>

 <?php
 if($file_uploaded)
 {
	 if($done)
	 {
	 echo '<font color="green">'.$done.'</font>';
	 }
	 else if($error)
	 {
	 echo '<font color="red">'.$error.'</font>';
	 }
	 echo '<br /><br />';
 }
 ?>

<form enctype="multipart/form-data" action="validate_image_upload.php" method="POST">
    
<!-- MAX_FILE_SIZE must be set before the input element -->
<input type="hidden" name="MAX_FILE_SIZE" value="2048000" />

<!-- The name from the $_FILES array is determined by the input name -->
Select an Image: <input name="image_file" type="file" /> <input type="submit" value="Upload" />

</form>

</center>

 </body>
</html>

NOTE Please make sure the config.php file is located in the same folder with validate_image_upload.php, and the folder where the image file will be moved is writable.


Comment via Facebook

comments

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)

POSTING RULES:

  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.