3

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?

Victor Nicollet
  • 24,361
  • 4
  • 58
  • 89
  • 2
    Does http://fi2.php.net/manual/en/language.operators.errorcontrol.php#98895 help - are you using a custom error handler or something? If for some reason it absolutely won't work, you can always use output buffering to catch the error message, but that's a bit ugly. – Shadikka Jan 18 '11 at 09:22
  • did you try : try catch issue ? – Haim Evgi Jan 18 '11 at 09:23
  • @Shaddika: you might want to post this as an answer, so that I may accept it. @Haim Evgi: it's not an exception. – Victor Nicollet Jan 18 '11 at 09:26
  • I'm not sure that try/catch would work as an exception isn't being thrown. – Matt Lowden Jan 18 '11 at 09:33

2 Answers2

7

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.

Matt Lowden
  • 2,586
  • 17
  • 19
  • Good stuff, does this do everything you need? – Matt Lowden Jan 18 '11 at 09:33
  • Well, the actual issue was correctly identified by Shaddika - there's a bug in my custom error handler that breaks the `@` construct. I've +1'ed your answer and will accept it unless Shaddika posts his comment as an actual answer instead in the next few minutes. – Victor Nicollet Jan 18 '11 at 09:36
  • How does this answer the question on how to detect errors with gd lib.. – Daniel W. Jan 21 '21 at 17:33
2

'@' 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

Ruslan Kabalin
  • 6,580
  • 2
  • 28
  • 20
  • The link you provide has a note explaining why your answer does not apply here - "Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions." – Victor Nicollet Jan 18 '11 at 09:32
  • Yep, but the same note explains how to make it work for "Error reporting" ones. – Ruslan Kabalin Jan 18 '11 at 09:42