I googled for this problem but there is no answer for it.
I want my PHP script to generate HTTP response in chunked( http://en.wikipedia.org/wiki/Chunked_transfer_encoding). How to do it?
Update: I figured it out. I have to specify Transfer-encoding header and flush it.
header("Transfer-encoding: chunked");
flush();
The flush is necessary. Otherwise, Content-Length header will be generated.
And, I have to make chunks by myself. With a helper function, it is not hard.
function dump_chunk($chunk)
{
echo sprintf("%x\r\n", strlen($chunk));
echo $chunk;
echo "\r\n";
}
A PHP response will always be chunked if you don't specify a content-length header, and a flush occurs. (which will happen automatically after x bytes, just don't know exactly how much).
This is a weird thing to care about. Is this some kind of academic/learning exercise or is there a real world problem you're trying to solve?
The output buffer will not be sent to the browser until it is full. The default size is
4096
bytes. So you either need to change the buffer size or pad your chunks. Also, the browser may have it's own minimum buffer before the page is displayed. Note that according to the Wikipedia Article about chunked encoding, sending a0\r\n\r\n
chunk terminates the response.If you want to change the output buffering size setting, I read that you cannot use
ini_set('output_buffering', $value)
. Instead, change the output buffering setting by adding the following to your php.ini file.Here's an example of padding your chunks
Here's a short version that demonstrates
0\r\n\r\n\
terminating the output:You should be able to use:
but you'll have to ensure yourself that the output follows the specifications.
Andriy F.'s solution worked for me. Here's a simplified version of his answer:
Although I don't understand why the
ob_flush()
call is needed. If someone knows, please comment.Working sample as of 16.02.2013
This has gotten a little vauge... if you don't mind big assed chunks, (0x1000 octets or so), then yes, PHP will make them.
PHP will generated the numbered sections, etc.
If you want to send tiny little chunks, as you might do with an AJAX client... well, I've combined the OPs question, with some research on PHP.NET, and it does look like he was on to a good thing.
$ echo -en "GET /chunked/ HTTP/1.1\r\nHost: ec\r\n\r\n" | nc localhost 80
Whether or not it will eventually squeeze out it out's own (incorrect) chunk count, remains to be seen... but I saw no sign of it.