How do you run a long PHP script and keep sending updates to the browser via HTTP?

Robin Rodricks picture Robin Rodricks · Jun 8, 2010 · Viewed 9.5k times · Source

How do you run a long PHP script and keep sending updates to the browser via HTTP?

Something to do with output buffering but I don't know exactly how.

Answer

CharlesLeaf picture CharlesLeaf · Jun 8, 2010

Output Buffering is thinking in the right direction, you start output buffering with ob_start() just like you would with sessions (session_start) somewhere in the top of your script, before any output is sent.

Then, you can use ob_flush and flush to keep flushing the output. For example, if you are in a foreach loop and at the end of each loop you want to output the new row and wait 1 second you would can do that.

But also look at set_time_limit, because otherwise people might experience a timeout after 30 seconds or so.

Another quick note, some browsers require a minimum number of bytes of output before they actually start showing it. I'm not sure what amound of bytes it was, I think it was around the 4000. Also, some browsers won't render certain elements (like tables) until they are closed. So flushing won't work there either.