PHP Image Uploads – Better File Type Checking

When working on a project I came across a neat snippet of code that will uses PHP’s image manipulation functions to check the uploaded image type. The majority of the time the filetype is checked using PHP’s string functions on the file name, as a string E.g.

$myFile = $_FILES['myFile']['name'];
$allowed_filetypes = array('.gif', '.JPEG');
$ext = substr($myFile, strpos($myFile,'.'), strlen($myFile)-1);

This is fine, but the contents of $myFile can be faked. A much better check for allowing only image file uploads would be to do the following – I thought this was quite neat:

if (!$img = @imagecreatefromgif($path_to_image)) {
  /* NOT a .GIF image */

imagecreatefromgif will return false if the image is not a GIF. A similar thing can be done for checking PNGs (see imagecreatefrompng) and JPEGs (see imagecreatefromjpeg).

Published by

Rob Allport

Web Developer based in Stoke-on-Trent Staffordshire Google+ - Twitter

One thought on “PHP Image Uploads – Better File Type Checking”

Leave a Reply

Your email address will not be published. Required fields are marked *