imagecreatefromstring - 捕获失败 - PHP

Lov*_*ock 2 php php-gd

我试图在给定 URL 时检测图像是否为图像。要从 url 保存图像,我使用了以下内容:

// create the image and save it
$imagefile = $URL;
$resource = imagecreatefromstring(file_get_contents($imagefile));
// X amount of quality is the last number
imagejpeg($resource, "images/covers/$imagepath.jpeg", 50);
imagedestroy($resource);
Run Code Online (Sandbox Code Playgroud)

$URL 只是用户提供的图片链接。

我尝试了以下方法:

$imagefile = $addBuildCover;
$resource = imagecreatefromstring(file_get_contents($imagefile));

if ($resource !== false) {
  $return['imageGood'] = true;  
} else {
  $return['imageBad'] = true;
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过该代码,并且返回了“imageBad”的正确 JSON 返回值,但在此之前它给了我一个错误:

Warning: file_get_contents(ewffw.png): failed to open stream: No such file or directory in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 116

Warning: imagecreatefromstring(): Empty string or invalid image in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 116
Run Code Online (Sandbox Code Playgroud)

我如何尝试捕获 URL 失败但实际上没有像上面那样返回错误?

Jon*_*Jon 6

imagecreatefromstring 不幸的是,如果您传递无效数据,则会发出警告,因此使用它会产生不必要的问题。

您将不得不使用错误抑制运算符将其关闭@

$resource = @imagecreatefromstring(file_get_contents($imagefile));
Run Code Online (Sandbox Code Playgroud)

使用这个运算符通常是不受欢迎的,但这种情况是您确实有合法用例的情况。

file_get_contents如果无法加载文件,此方法还将处理发出的警告。该函数的行为并没有那么糟糕(有一些方法可以合理确定地检查它是否会失败,例如is_readable),因此您可以检查代码而不是使用@,但是因为无论如何您都需要抑制错误并且它对您没有任何影响如果文件读取失败与否,@恕我直言,在前面打一个是完全有保证的。