0

Credit to https://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html for this example code.

If I run this code (ubuntu 16.04), I don't get any results in the browser (chrome) until the loop has finished. I don't see any output from my server side event until the entire script has finished processing.

This code does not work unless I flush 2M of data to the browser before starting the loop.

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function send_message($id, $message, $progress) {
    $d = array('message' => $message , 'progress' => $progress, );
    echo "id: $id" . PHP_EOL;
    echo "data: " . json_encode($d) . PHP_EOL;
    echo PHP_EOL;
    ob_flush();
    flush();
}

disable_buffer();    // send data to browser to initialize
for($i = 1; $i <= 4; $i++) {
    send_message($i, 'on iteration ' . $i . ' of 4' , $i*10);
    sleep(1);
}
send_message('CLOSE', 'Process complete', 100);

The only way I can get this to work is to use the function disable_buffer();

function disable_buffer() {
    @ini_set('zlib.output_compression', 'Off');
    @ini_set('output_buffering', 'Off');
    @ini_set('default_charset', 'utf-8');
    @apache_setenv('no-gzip', 1);
    echo str_repeat('.', 2222000).PHP_EOL;
    flush();
}

Specifically, it doesn't work without ...

echo str_repeat('.', 2222000).PHP_EOL; 
flush();

Why do I have to flush 2M of data to the browser? If I don't do this the browser doesn't see anything until the entire script is finished. If I send 2M first, then I can see the messages in the browser as soon as they are sent.

zDaniels
  • 600
  • 1
  • 10
  • 21
  • 1
    Most likely the web server does its own buffering. Make sure you have stuff like output compression (on the web server level, not just PHP) disabled completely. https://stackoverflow.com/questions/4706525/php-flush-not-working There’s lots of questions regarding such flushing problems here on SO, do some further research and see what might work on your system. – 04FS Jan 30 '19 at 08:30
  • Possible duplicate of [PHP Flush/ob\_flush not working](https://stackoverflow.com/questions/4481235/php-flush-ob-flush-not-working) – Nico Haase Feb 01 '19 at 08:40

0 Answers0