51

Right now in order to see the results, I have to wait until the entire code is done executing. It hangs until it's complete and stays loading. Once it's finished it shows all the information I was looking for.. Is there anyway to show this while the script is still running? So say if I have a print somewhere at the top of my code, I want it to show when it's called not when the script is done executing.

Anyone know how to do this?

Thanks

adam
  • 513
  • 1
  • 4
  • 4

4 Answers4

73

You can use output buffering like this:

ob_start();

echo('doing something...');

// send to browser
ob_flush();

// ... do long running stuff
echo('still going...');

ob_flush();

echo('done.');
ob_end_flush(); 
Rob Agar
  • 12,337
  • 5
  • 48
  • 63
  • 6
    It worked for me after I added `ob_implicit_flush(true)` before `ob_start()`; – Bivis Dec 21 '16 at 17:57
  • I had to add ob_implicit_flush(true) and also set output_buffering = Off in php.ini – embe Apr 02 '17 at 09:07
  • **ADD `flush();`** in some webservers the `ob_flush()` does not means that it will output the buffer to apache. [flush](http://php.net/flush) – JohnnyJS Mar 11 '18 at 09:04
  • 2
    Some browser only output if the filesize is larger then 1KB. This helped me: https://stackoverflow.com/a/4192086/2311074 – Adam Jul 24 '18 at 08:19
  • Had to use the ob_end_flush() to get smaller batches to echo and then start the buffer again. – Longblog Jun 22 '19 at 00:07
  • This worked great for running from CLI but for running in a browser, [@Adam's comment](https://stackoverflow.com/a/4192086/3291390) lead to the solution. – Stack Underflow Dec 23 '19 at 20:49
12

This one worked for me: (source)

function output($str) {
    echo $str;
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
}
Claudio
  • 5,078
  • 1
  • 22
  • 33
3

You can do that with output buffering. Turn on output buffering at the top of your script with ob_start(). That makes PHP to send no output to the browser. Instead its stored internally. Flush your output at any time with ob_flush(), and the content will be sent to the browser.
But keep in mind that output buffering is influenced by many other factors. I think some versions of IIS will wait until the script is finished, ignoring output buffering. And some Antivirus software on client side (Was it Panda?) might wait until the page is fully loaded before passing it through to the browser.

fab
  • 1,839
  • 15
  • 21
2

I had to put both ob-flush and flush as shown in this example:

for($i=10; $i > 0; $i--)
{
    echo "$i ...";
    flush();
    ob_flush();
    sleep(1);
}
agold
  • 6,140
  • 9
  • 38
  • 54