如何捕获无效的图像时,使用PHP imagecreatefromstring


How to catch invalid image when using PHP imagecreatefromstring

我正在使用imagecreatefromstring,目前验证正确的图像文件格式。

所以链接是:

swqkdwfibqwfwf

不起作用,因为它不是一个有效的文件类型。但是我刚刚发现了这个:

sibdlsibiwbifw.png

将发送没有错误从我的验证。我得到这个错误的图像链接,不返回和图像:

Warning: file_get_contents(etwteet.png): failed to open stream: No such file or directory in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 141
Warning: imagecreatefromstring(): Empty string or invalid image in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 141
Warning: imagejpeg() expects parameter 1 to be resource, boolean given in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 143

是否有一种方法可以捕获此错误,以便我可以停止代码处理并通知用户?

获取URL的代码:

$imagefile = image url;
$resource = imagecreatefromstring(file_get_contents($imagefile));

谢谢。克雷格。

通过所有可实现的验证,我认为最终需要捕获imagecreatefromstring上的错误。

带有错误处理程序…

PHP 5.3或更高版本支持以下语法。

set_error_handler(function ($no, $msg, $file, $line) {
    throw new ErrorException($msg, 0, $no, $file, $line);
});
try {
    $img = imagecreatefromstring(file_get_contents("..."));
} catch (Exception $e) {
    echo $e->getMessage();
}

@error_get_last

if (!$img = @imagecreatefromstring(file_get_contents("..."))) {
    $e = error_get_last();
    die($e['message']);
}

PHP 5.4或更高版本支持以下语法。

if (!$img = @imagecreatefromstring(file_get_contents("..."))) {
    die(error_get_last()['message']);
}