开发者

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开发者_Python百科 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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜