imagecreatefrompng error - how to detect and handle?

Victor Nicollet picture Victor Nicollet · Jan 18, 2011 · Viewed 9.7k times · Source

In my script, I have the following lines:

$test = @imagecreatefrompng($name);
if ($test) { ... }

I am certain that $name represents an existing file on the disk, but I must handle cases where that file is not a valid PNG file (either because of a transfer error or because of a malicious user). I wish to handle such cases by not doing anything at all.

However, given the above code, my PHP interpreter stops on the first line with the following error message:

imagecreatefrompng() [function.imagecreatefrompng]: 'foobar.png' is not a valid PNG file

Shouldn't '@' have suppressed this error message and had the function return falseas described in the documentation? How can I tell PHP that I know an error might happen and not interrupt the execution?

Answer

Matt Lowden picture Matt Lowden · Jan 18, 2011

You could use mime_content_type on the file.

$image = 'file.png';
if(is_file($image) && mime_content_type($image_type) == 'image/png'){
    // Image is PNG
}else{
    // Not PNG
}

This will ensure the image is a file and a PNG.