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

1

6

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.

Letter answered 5/8, 2012 at 21:15 Comment(5)
I'd say, unless proven wrong, you should be able to just echo out anything you need. Ensure you have set all real response headers you need to before starting the chunked response body. Also ensure that the request is HTTP/1.1 and chunked transfer encoding is supported. This should be transparent for CGI/FCGI.Kinesthesia
I couldn't find how to supply a HTTP trailer from a CGI. Anything a CGI outputs after a double newline is treated by Apache as the response body.Letter
Yes but as the specification goes, a chunked respose is only in the response body, so this should not be a problem. Or have I read the specs wrong?Kinesthesia
@Kinesthesia While you are absolutely correct in that semantically there is no difference between response body and trailers in terms of the way they would be output, since Apache is handling the chunking you would need to somehow explain to it that these last lines of data were trailers and not just another chunk. Trailers should follow the last 0-length chunk. AFAIK there is no way to do this. The only thing I can think of would be to turn of whatever mechanism in Apache handles the chunking, and manually implement in your PHP script. Which is possible but a huge PITA...Ludwig
What are you trying to accomplish that you need a chunked response?Pressmark
C
3

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();
Cottonseed answered 15/8, 2012 at 6:54 Comment(1)
Mocking the chunked stream is not what I'm looking for, of course I can mock it myself by following the spec. But what I really want is to test my code against a real response that is guaranteed to be correct. For me it's a piece of mind thing.Letter

© 2022 - 2024 — McMap. All rights reserved.