There is a special function in PHP called flush(), which is not really related to output buffering because it works with standard output, however it is so very similar to what we've just been looking at that it makes sense to cover it here.
Flush() sends all output out immediately, without waiting for the end of the script, and you can call it as often as you want. Calling flush() has the effect of making the browser update with new content. Take a look at this example script:
Author's Note: Internet Explorer has an "optimisation" that makes it only render a page after it has received the first 256 bytes whether or not you use flush() - you might find these example scripts do not work as described in IE. That is not to say the concept is wrong - merely that there is not enough room here to demonstrate a longer example! To make the scripts work, make them output at least 256 characters before the first call flush() - in your own scripts, this will not be a problem.
This page is loading...<br /> <?php sleep(2);?> Almost there...<br /> <?php sleep(2);?> Done.<br />
If you try that you will see the page appears all at once, having taking a little over four seconds to load - not a very helpful progress monitor! Now consider the following script, making use of flush():
This page is loading.<br /> <?php flush();sleep(2);?> Almost there...<br /> <?php flush();sleep(2);?> Done.<br />
This time you will literally see the page loading - each line will appear one by one, as seen in these screenshots:
Using flush() is good for all sorts of things, but as you have seen it is particularly good when you are executing a long script and want to keep users informed. It takes very little work to print out "Please wait - generating your file" and calling flush() before creating a 500MB file - you can even follow up with printing out "File created - click here to download", so that your scripts feel much more interactive.