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.
<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>
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.
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Compressing output >>
Previous chapter: Other OB functions
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.