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>

Warning

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 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>
    </body>

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

Loading...

Figure 11-1. Loading...

...loading...

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

Figure 11-3. Done!

You can use JavaScript ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.