I want to download the first 16 KB of a given URL and I'm using the GuzzleHTTP library for this. Checking the Content-Length
header or sending the Ranges
header will not work for my purposes, since the server may not send/accept any of these headers.
Is there a way I can set the maximum amount of content that should be retrieved by Guzzle?
Yes, there is a way. Use stream
option to download content by chunks, not all at once.
$response = $client->request('GET', '/stream/20', ['stream' => true]);
// Read bytes off of the stream until the end of the stream is reached
$body = $response->getBody();
$buffer = '';
while (!$body->eof() && (strlen($buffer) < 16384)) {
$buffer .= $body->read(1024);
}
$body->close();
With this solution you are able to control the amount of content you want to download.