Section 11.8. Flushing Output


11.8. Flushing Output

If you aren't using output buffer, you can still use the flush( ) to send all output immediately, without waiting for the end of the script. You can call flush( ) as often as you want, and it makes your visitor's browser update with new content. For example:

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

Internet Explorer has an "optimization" that makes it render a page only after it has received the first 256 bytes, whether or not you use flush( )you might find these example scripts do not work in IE as described. To make the scripts work, make them output at least 256 characters before the first call flush( ).


If you try that, you will see that the page appears all at once, having taken a little over four seconds to loadnot 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>     </body> 

This time, you will literally see the page loadingeach line will appear one by one, as seen in Figures 11-1, 11-2, and 11-3.

Figure 11-1. Loading...


Figure 11-2. ...loading...


Figure 11-3. Done!


You can use JavaScript to alter what has been output already, like this:

     <html>     <body>     <div >     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 locates the DIV HTML element on the page, then sets its innerHTML property to different messages as the script loadsa 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 call flush( ) before creating a 500MB fileyou can even follow up with printing out "File created - click here to download," so that your scripts feel much more interactive.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net