简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM