gpt4 book ai didi

php - 使用 PHP imagecreatefromstring 时如何捕获无效图像

转载 作者:行者123 更新时间:2023-12-02 17:38:03 26 4
gpt4 key购买 nike

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

关于php - 使用 PHP imagecreatefromstring 时如何捕获无效图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24214685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com