【问题标题】:How to catch invalid image when using PHP imagecreatefromstring使用 PHP imagecreatefromstring 时如何捕获无效图像
【发布时间】:2014-08-04 13:35:01
【问题描述】:

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

谢谢。克雷格。

【问题讨论】:

  • 如果您只是在尝试对源文件执行任何操作之前检查源文件是否存在,则可以轻松防止这种情况发生。 file_exists() 会很好地完成这项工作。 ;)
  • 太棒了,一会儿试试,然后报告。

标签: php imagecreatefrompng


【解决方案1】:

通过所有可实施的验证,我相信最终需要在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']);
}

【讨论】:

    猜你喜欢
    • 2010-09-11
    • 2011-10-17
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多