views:

973

answers:

9

For example, if I have an echo statement, there's no guarantee that the browser might display it right away, might display a few dozen echo statements at once, and might wait until the entire page is done before displaying anything.

Is there a way to have each echo appear in a browser as it is executed?

A: 

Start your investigation here:

http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts

Ian P
Does that apply even if PHP is not running as a CGI?
Thomas Owens
+1  A: 

You can call flush() in PHP, but there are several other places that the output may be held (e.g. on the webserver). If you are using output buffering you need to call ob_flush() also.

You may also find that some browsers will not render the page until the html is valid which won't be until all the tags are closed (like body, html)

Tom Haigh
+4  A: 

You can use flush() to force sending the buffer contents to the browser.

You can enable implicit flushing with "ob_implicit_flush(true)".

blueyed
+3  A: 
function printnow($str, $bbreak=true){
    print "$str";
    if($bbreak){
     print "<br />";
    }
    ob_flush(); flush();
}

Obviously this isn't going to behave if you pass it complicated objects (or at least those that don't implement __toString) but, you get the idea.

Mark Biek
A: 

flush() is part of the answer. At least until a year ago, using flush was unreliable in Safari, however. Depending on your scenario, I'd look into solutions involving javascript. Maybe the various implementation of progress bars have code/ideas you can recycle.

MattW.
+2  A: 

As others pointed out, there are places where things can get hung up besides PHP (e.g., the web server or the client's browser). If you really want to ensure that information is displayed as it becomes available, you'll probably need some AJAX-based solution. You would have one PHP script that handles display and another that does calculations, and have the display script make AJAX requests to the other. jQuery has some pretty simple AJAX functions that might help you there.

You'd also want to have a fallback in case the browser doesn't support/has disabled JavaScript that would just be the standard page that may not display content until the end.

Randy
A: 

I'd suggest using AJAX.

Omar Kooheji
A: 

Enabling implicit flush as blueyed said should do the trick since it calls flush after every echo however some browsers also require no-cache headers to be set. Here is what I use. Your mileage may vary depending on the browser.

header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');
gradbot