I'm trying to output some large binary arrays to an HTTP response using the following code:
$bin = NULL; $strLenToOutput = 8000; for ($i=0; $i < $strLenToOutput; $i ) { $bin .= pack("C", 1); } header('Content-Description: File Transfer'); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=test.bin"); header("Content-Length: filesize=" . strlen($bin)); header("Cache-Control: no-cache"); echo $bin;
When the string to be output is relatively short, less than or equal to 8000, the above code works fine. But if the string length is increased to 8001, I get the following error in Postman:
Parse Error: The server returned a malformed response
I'm running PHP7.4 on Apache V2.4.46, all settings are default.
What am I doing wrong here? Is it the PHP code or some settings on Apache2 that need to be changed?
Please provide guidance, thanks in advance.
Update: If I remove the following line that sets the file length, the PHP code works fine. I guess the problem is that I should let PHP handle this part itself.
//header("Content-Length: filesize=" . strlen($bin));
The problem lies in the way the Content-Length header is set. The original code sets a header
should be set like this:
Extra text "filesize=" in the header will only confuse the client's parsing of the response. When Content-Length is less than or equal to 8000, the client may have a way to recover, but it cannot handle the situation when Content-Length is greater than or equal to 8001