search

Home  >  Q&A  >  body text

When using echo to output a large binary string to an HTTP response in PHP, the server returned a malformed response.

<p>I'm trying to output some large binary arrays to an HTTP response using the following code: </p> <pre class="brush:php;toolbar:false;">$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;</pre> <p>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: </p> <pre class="brush:php;toolbar:false;">Parse Error: The server returned a malformed response</pre> <p>I'm running PHP7.4 on Apache V2.4.46, all settings are default. </p> <p>What am I doing wrong here? Is it the PHP code or some settings on Apache2 that need to be changed? </p> <p>Please provide guidance, thanks in advance. </p> <p>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. </p> <pre class="brush:php;toolbar:false;">//header("Content-Length: filesize=" . strlen($bin));</pre></p>
P粉328911308P粉328911308457 days ago512

reply all(1)I'll reply

  • P粉966335669

    P粉9663356692023-08-29 09:05:32

    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

    reply
    0
  • Cancelreply