我正在尝试从服务器下载图像,但是有时找不到图像(服务器返回" 404"(,所以我想下载占位符图像或只是跳过此图像URL。我现在拥有的是:
foreach($images as $image){
$handle = curl_init($image);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
$image = "https://placehold.it/1200x800";
}
curl_close($handle);
$http_client = new Client(array(
'base_uri' => '',
'verify' => false,
));
try {
$res = $http_client->get($image);
$name = substr($image, strrpos($image, '/') + 1);
Storage::put($vendor_code."/".$name, $res->getBody());
} catch (Exception $ex) {
Log::error($ex);
}
}
,但即使这样,我仍然有一个例外,没有找到图像
有任何帮助吗?
谢谢
我尝试了您的代码,并且$ httpcode响应始终为0,因为您从未真正执行卷发。在curl_setopt系列之后尝试一下:
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
来自文档中有两种支持的方法:
传递字符串以指定将存储响应主体内容的文件的路径:
$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);
传递从fopen((返回的资源来编写对PHP流的响应:
$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);
使用'save_to'
的第三个选项是 doverated :
传递psr http message streaminterface对象将响应主体流到打开的PSR-7流。
$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttpPsr7stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);
阅读有关Guzzleink的更多信息。