PHP best way to check if file is an image

By | October 23, 2011

The getimagesize function of php provides lot of information about an image file , including its type. The type can be used to check if the file is a valid image file or not.

To check if a file is an image or not, use the function

function is_image($path)
{
	$a = getimagesize($path);
	$image_type = $a[2];
	
	if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP)))
	{
		return true;
	}
	return false;
}

$a[0] and $a[1] are the width and height of the image.
$a[2] has the image type.

Other image formats include :

[IMAGETYPE_GIF] => 1
[IMAGETYPE_JPEG] => 2
[IMAGETYPE_PNG] => 3
[IMAGETYPE_SWF] => 4
[IMAGETYPE_PSD] => 5
[IMAGETYPE_BMP] => 6
[IMAGETYPE_TIFF_II] => 7
[IMAGETYPE_TIFF_MM] => 8
[IMAGETYPE_JPC] => 9
[IMAGETYPE_JP2] => 10
[IMAGETYPE_JPX] => 11
[IMAGETYPE_JB2] => 12
[IMAGETYPE_SWC] => 13
[IMAGETYPE_IFF] => 14
[IMAGETYPE_WBMP] => 15
[IMAGETYPE_JPEG2000] => 9
[IMAGETYPE_XBM] => 16
[IMAGETYPE_ICO] => 17
[IMAGETYPE_UNKNOWN] => 0
[IMAGETYPE_COUNT] => 18

Note :

1. mpeg videos are detected as IMAGETYPE_ICO !!

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

7 Comments

PHP best way to check if file is an image
  1. Vladimir

    Link: “http://php.net/manual/en/function.getimagesize.php”.
    Quote: “Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead”.
    Link to description of that extension: “http://php.net/manual/ru/book.fileinfo.php”.

  2. Tristram Shorter

    Hey, this is a really good solution. I spent ages looking for a decent function in the php manual, but this really solves my problem!
    Thanks a lot!
    Tristram

  3. coder

    it’s really helpfull !

    i simply added “@” before the getimagesize to prevent php outputing error messages on screen if it fails getting image size :
    $a = @getimagesize($path);

    Thanx :D

Leave a Reply

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