我正在尝试从服务器下载图像,但有时图像找不到(服务器返回"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);
}
}但即便如此,我仍然会得到一个异常,即找不到图像
有什么需要帮忙的吗?
谢谢
发布于 2019-07-03 02:10:13
我测试了您的代码,$httpCode响应总是为0,因为您从未实际执行curl。在curl_setopt行之后尝试一下,如下所示:
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);发布于 2019-07-03 02:17:47
从文档中下载文件有两种受支持的方法:
传递一个字符串以指定将存储响应正文内容的文件的路径:
$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'的第三个选项是不建议使用的
传递一个Psr\Http\Message\StreamInterface对象,将响应正文传输到一个开放的PSR-7流。
$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);阅读有关Guzzle Sink的更多信息。
https://stackoverflow.com/questions/56857530
复制相似问题