PHP: How to get the Content-Length from stream request for chunk download

30 Views Asked by At

I'm attempting to download archives from an external site in chunks. However, I'm encountering an issue where the Content-Length header, which I'm trying to retrieve using get_headers(), is not present.

Has anyone else experienced this issue when saving chunked responses and trying to retrieve the Content-Length?

$options = array(
    'http' => array(
        'header' => "Authorization: Bearer $accessToken\r\n"
    )
);
$context = stream_context_create($options);

// I'm trying to get the Content-Length to limit the file download to files larger than 1GB.
// $file_headers = get_headers($sourceFile, 1, $context);
// if($file_headers["Content-Type"])

$sourceFileStream = fopen($sourceFile, 'rb', false, $context);

How can I retrieve the Content-Type or the size of the response stream?

1

There are 1 best solutions below

0
Joe On

I assume the response is sent with Transfer-Encoding: chunked

Therefore, there is no Content-Length header field (RFC 7320): A sender MUST NOT send a Content-Length header field in any message that contains a Transfer-Encoding header field.

But you're lucky – the RFC also provides an algorithm to decode a chunked transfer and get its length.