繁体   English   中英

使用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']);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM