Victor Nicollet
Victor Nicollet

Reputation: 24587

imagecreatefrompng error - how to detect and handle?

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?

Upvotes: 3

Views: 12202

Answers (2)

Ruslan Kabalin
Ruslan Kabalin

Reputation: 6908

'@' is designed to suppresses errors, and you probably get the warning message.

You can do that using exceptions, e.g.

try {
    $test = imagecreatefrompng($name);
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

See more here

Upvotes: 2

Matt Lowden
Matt Lowden

Reputation: 2616

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.

Upvotes: 7

Related Questions