Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate Chunked response with a Trailer in Apache/PHP?

I know I can generate chunked response in PHP simply by introducing a sleep() in the output.

But is it possible to also generate a Trailer HTTP section in PHP? If not, is it possible in general in Apache 2.2?

I need it for testing purposes.

like image 644
rustyx Avatar asked Nov 03 '22 18:11

rustyx


1 Answers

PHP will send a chunked response by default if headers are sent and no Content-Length header was specified. If you're familiar with the HTTP spec, this is the only logical thing to do since the client on the other end needs to know when the HTTP message you're sending ends so it can stop reading.

If you want to do this manually, you need to ...

  1. Send the appropriate headers yourself and call flush()
  2. Manually output the chunked HTTP message

So you might do something like the following. The idea is that you need to manually send your own headers and manually chunk your own message. If you simply don't send a Content-Length header, however, PHP will send a chunked message for you by default.

header("Transfer-encoding: chunked");
header("Trailer: X-My-Trailer-Header");
flush();

echo dechex(strlen($myChunk)) . "\r\n";
echo $myChunk;
echo "\r\n";
flush();

echo "0\r\n";
flush();

echo "X-My-Trailer-Header: some-value\r\n";
flush();
like image 51
rdlowrey Avatar answered Nov 11 '22 05:11

rdlowrey