How to make PHP generate Chunked response

Morgan Cheng picture Morgan Cheng · Mar 20, 2010 · Viewed 33.4k times · Source

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";
}

Answer

Evert picture Evert · Sep 23, 2011

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?