Link to home
Start Free TrialLog in
Avatar of Zoe Zoe
Zoe Zoe

asked on

What's the difference between exif_imagetype and finfo when trying to determine file type of an uploaded image? Which is more secure?

I've seen the following two code snippets to check file type. What's the difference between the two and which is more reliable/secure?

$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
	$finfo->file($_FILES['upfile']['tmp_name']),
	array(
		'jpg' => 'image/jpeg',
		'png' => 'image/png',
		'gif' => 'image/gif',
	),
	true
)) {
	throw new RuntimeException('Invalid file format.');
}

Open in new window


$type = exif_imagetype($file['tmp_name']);
if ($type) {
	$extension = image_type_to_extension($type);
	if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {

	} else {
	  $this -> msg = 'Please upload image with the following types: JPG, PNG, GIF';
	}
} else {
	$this -> msg = 'Please upload image file';
}

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

The most reliable and secure method is to create an image resource from the uploaded file, create a new image file, and store the new file, discarding the old file.  Attacks via images are kind of a decade ago, and we don't let that happen any more.  Filter Input Escape Output.

A code sample might look like this.  If the image extension is not what you expect from the image, you're almost certainly dealing with attack data.  Just don't use that stuff.
// ACQUIRE THE ORIGINAL IMAGE
$image_ext = explode('.', $image_url);
$image_ext = end($image_ext);
$image_ext = trim(strtoupper($image_ext));
switch($image_ext)
{
    case 'JPG' :
    case 'JPEG' :
        $image = @imagecreatefromjpeg($image_url);
        if ($image) break;

    case 'PNG' :
        $image = @imagecreatefrompng($image_url);
        if ($image) break;

    default : trigger_error("UNKNOWN IMAGE TYPE: $image_url", E_USER_ERROR);
}

Open in new window

SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial