When using echo to output a large binary string to an HTTP response in PHP, the server returned a malformed response.
P粉328911308
P粉328911308 2023-08-28 10:26:38
0
1
443

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));

P粉328911308
P粉328911308

reply all (1)
P粉966335669

The problem lies in the way the Content-Length header is set. The original code sets a header

header("Content-Length: filesize=" . strlen($bin));

should be set like this:

header("Content-Length: " . strlen($bin));

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

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!