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.