2

I'm developing a long running php script that compiles scraped information from multiple sources, organizes them, and caches them in a database.

As this script has a very high runtime, I'd like to print out runtime status reports in order to track the progress.

for ($i = 1; $i<= 10; $i++) {
    echo "Starting iteration #$i\n";
    set_time_limit(40);
    echo "Time Limit set, starting 10 second sleep.\n";
    sleep(10);
    echo "Finishing iteration #$i\n\n";
}
echo "Iterations Finished.";

would output:

Starting iteration #1

Time Limit set, starting 10 second sleep

then wait 10 seconds and output:

Finishing iteration #1

Starting iteration #2

Time Limit set, starting 10 second sleep

then right before the php finishes parsing, it will output:

Iterations Finished.

What is the best way to achieve this?

Community
  • 1
  • 1
Korvin Szanto
  • 4,531
  • 4
  • 19
  • 49

2 Answers2

3

If you are running PHP from the CLI you can output directly to stdout, without having to wait for the script to end, using :

$handle = fopen('php://stdout', 'r');
fwrite($handle, $output);

If run from CGI, which would be really bad for a script like this, you would have to change how the buffer acts with flush();

Tom
  • 1,647
  • 11
  • 24
  • My php is currently installed as CGI, what makes it bad? – Korvin Szanto Sep 17 '11 at 22:23
  • `function flush2 (){ echo(str_repeat(' ',256)); if (ob_get_length()){ @ob_flush(); @flush(); @ob_end_flush(); } @ob_start(); }` was the solution in my case. – Korvin Szanto Sep 17 '11 at 22:24
  • Don't know why, but on my current environment `echo` calls were buffered, so I get my output only when script ends. Your solution helped, because `fwrite` to stdout shows messages immediately. – userlond Jul 26 '17 at 03:56
1

Try writing the runtime status reports to a file, then viewing live updates of the file using ajax, per this question: Live feed of an updating file

Community
  • 1
  • 1
someone
  • 1,468
  • 8
  • 9