1

I try to output data from PHP to the browser immediately everytime there is some data to send. I've searched for a solution and ended up with the code below where each line should be shown in the browser every second.

This should work according to the PHP manual and other sites. But for me it doesn't. The browser waits for 5 seconds and displays everything at once. I have tried on latest versions of Firefox, Chrome and IE and I can't figure out why the result isn't shown after each ob_flush/flush. Can anyone explain?

<?php
header( 'Content-type: text/html; charset=utf-8' );
ob_implicit_flush(true);
ob_start();

for ($i = 0; $i<5; $i++){
    echo "<p>{$i}. Displaying one line...</p>";
    echo str_pad('',4096)."\n";   

    ob_flush();
    flush();

    sleep(1);
}

echo "Done.";
ob_end_flush();
?>

Note: I have also experimented on using ob_end_flush at the beginning, removing the header line, sending longer echo strings, read other posts on Stack Overflow, etc.. The browser still waits until the output is done.

Gowire
  • 1,046
  • 6
  • 27
  • 1
    Possible duplicate of [How to disable output buffering in PHP](https://stackoverflow.com/questions/8882383/how-to-disable-output-buffering-in-php) – rak007 Sep 28 '17 at 08:58
  • [Comments on the PHP manual page](https://www.php.net/manual/en/function.ob-flush.php#109699) suggest this is a longstanding decision made by the browser vendors so is not a code or server platform specific issue. – Martin May 08 '22 at 21:40

1 Answers1

0

This simple code works in Chrome and Edge. The numbers are displayed as the flush occurs. But not in Firefox. In Firefox everything is displayed when the PHP script ends.

<?php
for ($i = 0; $i < 5; $i++)
{
    echo "i==$i<br>\n";
    flush();
    @ob_flush();
    sleep(1);
}
Santo
  • 71
  • 3