Imagecreatefrompng error - how to detect and process?

In my script, I have the following lines:

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

I am sure it $nameis an existing file on disk, but I must handle cases where this file is not a valid PNG file (due to a transmission error or due to a malicious user). I want to deal with such cases without doing anything.

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

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

Shouldn't @'suppress this error message and return the function falseas described in the documentation? How can I tell PHP that I know that an error may occur and not interrupt execution?

+3
source share
2 answers

You can use mime_content_typein the file.

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

This ensures that the image is a file and PNG.

+7
source

'@' is intended to suppress errors, and you are likely to receive a warning message.

You can do this using exceptions like

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

More here

+1
source

Source: https://habr.com/ru/post/1786100/


All Articles