Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing PHP output continuously?

Tags:

php

I have a script that runs for like 1 hour. I have 2 webhosts, in one of them, I can see the output in realtime, (it loops a million times and echoes stuff) while on the other webhost, I have to wait until the script is finished running before I see any output at all.

How can I change the settings to show the output in realtime? I guess this is a php.ini thing.

Adding code: This code will output while executing in the first server, but not in the second server. Additional info, if i put the value of 1015 lower, the first server waits with outputting. So it seems that my first server is flushing every 1015 characters, while the second does not.

while ($a++ < 5) {
  $b = 0;
  while ($b++ < 1015) {
    echo "H";
  }
  echo "<br><br>\n";
  sleep(1);
}

On my second server, output buffering is off, and i tried turning on implicit_flush to no avail.

like image 875
Kristian Rafteseth Avatar asked Mar 10 '13 05:03

Kristian Rafteseth


2 Answers

This is related to output buffering. If output buffering is turned on, the output is not sent to the client immediately but will wait until a certain amount of data buffered. This usually increases performance but will cause problem like yours.

The simple solution doesn't require changing any php.ini settings, but simply put this at the beginning of your script:

<?php
  while (@ob_end_flush());
?>

This will flush and disable all output buffering at once.

(Source: http://www.php.net/manual/en/function.ob-end-flush.php#example-460)

You may also want to read the PHP manual on Output Control. The related php.ini settings are listed here.

If you want to make sure things are being sent (i.e. before a time-consuming task), call flush() at the appropriate times.


Edit:

In fact browsers may have their own buffers, especially when Content-Type is not explicitly set (the browser need to sniff the MIME-type of the file). If this is the case, you cannot control the browser's behaviour.

One way that might solve it is to explicitly set the Content-Type:

header("Content-Type: text/plain"); // if you don't need HTML
// OR
header("Content-Type: text/html");

But this is not guaranteed to work. It works on my Firefox but not Chrome.

Anyway, your final code should look like:

header("Content-Type: text/html"); // Set Content-Type
while (@ob_end_flush()); // Flush and disable output buffers
while ($a++ < 5) {
  $b = 0;
  while ($b++ < 1015) {
    echo "H";
    //flush(); // In fact because there is no significant delay, you should not flush here.
  }
  echo "<br><br>\n";
  flush(); // Flush output
  sleep(1);
}
like image 200
Alvin Wong Avatar answered Nov 09 '22 00:11

Alvin Wong


Try calling flush periodically. If you are using output buffering, you may want to turn that off with a sequence of ob_end_flush or use ob_flush as well.

like image 24
icktoofay Avatar answered Nov 08 '22 23:11

icktoofay