Flushing output

void flush ( void )

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.

<HTML>
<BODY>
This page is loading...<br />
<?php sleep(2); ?>
Almost there...<br />
<?php sleep(2); ?>
Done.<br />
</BODY>
</HTML>

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():

<HTML>
<BODY>
This page is loading.<br />
<?php flush(); sleep(2); ?>
Almost there...<br />
<?php flush(); sleep(2); ?>
Done.<br />
</BODY>
</HTML>

This time you will literally see the page loading - each line will appear one by one, as seen in these screenshots:




Now take you know it is possible to construct a page piece by piece, take a look at this bit of code - JavaScript is now used to alter what is there already, which makes for a much nicer-looking progress meter.

<HTML>
<BODY>
<DIV ID="flushme">
Hello, world!
</DIV>
<?php flush(); sleep(2); ?>
<SCRIPT>
d = document.getElementById("flushme");
d.innerHTML = "Goodbye, Perl!";
</SCRIPT>
<?php flush(); sleep(2); ?>
<SCRIPT>
d.innerHTML = "Goodnight, New York!";
</SCRIPT>
</BODY>
</HTML>

The JavaScript in there locates the DIV HTML element on the page, then sets its innerHTML property (the contents of the DIV) to different messages as the script loads - a simple, yet effective way to handle keeping users up to date while a script loads.

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.

 

Next chapter: Compressing output >>

Previous chapter: Other OB functions

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar