简体   繁体   中英

How to use guzzle to detect we are going to get a huge HTTP respond, before we even start to download the respond

We are still using legacy Guzzle 3.x.

Time to time, we need to send a HTTP GET respond to affiliate pixel fire URL.

Most of the time, we are expecting a few kb text respond.

However, some affiliates will send us a huge binary file, which we are not interested.

We would like to detect such scenario earlier, before even start to waste time to download the unnecessary binary file.

$url = 'http://speedtest.ftp.otenet.gr/files/test1Gb.db';

$client = new \Guzzle\Http\Client();

echo "1) Grab 1GB file...\n";

$s = $client->get($url,
    array(
        'timeout' => 5,         // Response timeout
        'connect_timeout' => 5, // Connection timeout
    )
);

echo "2) Grab 1GB file...\n";

// Code will "hang" here to wait 1GB file finished download.
$response = $s->send();

echo "Grab 1GB file done\n";

// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
    $content_length = $response->getHeader('Content-Length');
    // If the response is too large, we will reject it.
}

So, our code will spend a huge amount of time in executing

$response = $s->send();

If we can know this affiliate is going to send us an unnecessary 1GB binary file, we can give up earlier.

May I know, is there any way to know our respond size, even before we spend time to start downloading the unnecessary huge respond?

It's not a direct answer, but if migrate to Guzzle 6, you will be able to use streaming responses.

$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'URL', ['stream' => true]);
// Only headers are downloaded here.
$response->getHeader('Content-Length');

I think that Guzzle 3 supports something like this, but I'm not sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM