如何在使用PHP imagecreatefromstring时捕获无效图像
我正在使用imagecreatefromstring,目前正在验证图像文件格式是否正确 因此,以下链接:如何在使用PHP imagecreatefromstring时捕获无效图像,php,imagecreatefrompng,Php,Imagecreatefrompng,我正在使用imagecreatefromstring,目前正在验证图像文件格式是否正确 因此,以下链接: swqkdwfibqwfwf 无法工作,因为它不是有效的文件类型。但我刚刚发现: sibdlsibiwbifw.png 将从我的验证中发送,没有错误。对于未返回的图像链接和图像,我收到此错误: Warning: file_get_contents(etwteet.png): failed to open stream: No such file or directory in /var/
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));
谢谢。Craig.通过所有可实现的验证,我相信最终需要捕获
imagecreatefromstring
上的错误
使用错误处理程序。。。
包含PHP5.3或更高版本上提供的sytax
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();
}
if (!$img = @imagecreatefromstring(file_get_contents("..."))) {
die(error_get_last()['message']);
}
使用@
和错误\u get\u last
。。。
包含PHP5.4或更高版本上提供的sytax
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();
}
if (!$img = @imagecreatefromstring(file_get_contents("..."))) {
die(error_get_last()['message']);
}
请看这里:如果您在尝试对源文件执行任何操作之前只检查源文件是否存在,就可以很容易地防止这种情况<代码>文件\u exists()将很好地完成这项工作。;)太好了,我马上就去试试,然后回来汇报。