Handling 404 errors while downloading image

Viewed 490

I am trying to download images from a server, but sometimes the images are not found (the server returns a "404") so I want to download a placeholder image or just skip this image URL. What I have now is:

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);
    }
}

But even so, I still get an exception that the image is not found

Any help, please?

Thanks

2 Answers

I tried your code, and the $httpCode response is always going to be 0, due to the fact that you never actually execute the curl. Try it after the curl_setopt line, like so:

curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($handle); 
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

From the docs there are two supported ways to download a file:

Pass a string to specify the path to a file that will store the contents of the response body:

$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);

Pass a resource returned from fopen() to write the response to a PHP stream:

$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);

The third option using the 'save_to' is deprecated:

Pass a Psr\Http\Message\StreamInterface object to stream the response body to an open PSR-7 stream.

$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);

Read more about Guzzle Sink.

Related