Find an Image’s Dimensions and MIME Type with PHP

What’s the easiest way to figure out the width and height of an image, as well as the format of the file, in PHP? Given that the existence of a core function for practically everything is one of the language’s strengths, it’s unsurprising that it’s pretty easy.

The getimagesize() function returns an array containing the width and height and the content type.

//Basic usage
$info = getimagesize($filename);
$width = $info[0];
$height = $info[1];
$format = $info['mime'];

//Alternate one-liner suggested by the manual
list($width, $height, $type, $attr) = getimagesize($filename);

This function is really useful for handling image uploads, since you can’t necessarily trust the MIME type that $_FILES reports. The function actually inspects the file to ascertain the type, rather than relying on what the client reports. Also, you may want to make sure that the uploaded images match the dimensions you have in mind.

Here’s how I like to handle it:

$imgdata = getimagesize($_FILES['image_upload']['tmp_name']);

if ($imgdata[0] > 640 || $imgdata[1] > 480) {
	$errors[] = "Your image is too big!";
}

if (!in_array($imgdata['mime'], array( 'image/gif', 'image/png', 'image/jpeg', 'image/pjpeg' ))) {
	$errors[] = "Your file should be a PNG, JPG or GIF!";
}