Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guzzle 6.0 download file using request headers

I can't find any example of how to download a remote file using Guzzle 6.0. I need to pass headers in the GET request.

I have looked at the documentation which isn't helpful at all.

I came up with this but it still doesn't download a file

require_once('vendor/autoload.php');

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

$client = new Client();

$response = $client->request('GET', '/stream/20', [
    'headers' => [
        'Authorization: Token token' => 'df456g4fd564gfs65dg45s6fdg4dsf5g4sd65g', 
        'Cache-Control' => 'no-cache', 
        'Content-Type' => 'application/pdf'
    ],
    'sink' => 'https://example.com/path/to/file',
]);

Has anyone successfully downloaded a file using request headers?

like image 826
Peter Griffin Avatar asked Oct 15 '25 16:10

Peter Griffin


1 Answers

I think you got confused.

Where you have '/stream/20' is the url of where the file is you want to download.

The sink part is where you want to save your image.

Try this....

require __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

$client = new Client();

$resource = fopen('test.pdf', 'w');

$response = $client->request('GET', 'https://example.com/path/to/file', [
    'headers' => [
        'Authorization' => 'Token token=df456g4fd564gfs65dg45s6fdg4dsf5g4sd65g', 
        'Cache-Control' => 'no-cache', 
        'Content-Type' => 'application/pdf'
    ],
    'sink' => $resource,
]);

echo 'downloaded';
like image 67
AdRock Avatar answered Oct 19 '25 13:10

AdRock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!