Search code examples
phpflush

Why do I need `str_pad('',4096)` to make PHP flushing work?


For example,

this doesn't work (Firefox 21, IE8):

<?php
function flush_buffers(){
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
}  
ob_start();
echo 'Text 1<br />';
flush_buffers();
Sleep(2);
echo 'Text 2<br />';
flush_buffers();
Sleep(2);
echo 'Text 3<br />';
flush_buffers();
Sleep(2);
echo 'Text 4<br />';
?>

But this one works:

<?php
function flush_buffers(){
    echo str_pad('',4096);
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
}  
ob_start();
echo 'Text 1<br />';
flush_buffers();
Sleep(2);
echo 'Text 2<br />';
flush_buffers();
Sleep(2);
echo 'Text 3<br />';
flush_buffers();
Sleep(2);
echo 'Text 4<br />';
?>

I have PHP 5.4.11 VC9 and Apache 2.4.3 (apacheLounge) running on Win XP SP3.


Solution

  • Some browsers include their own internal buffer in order to download and display more efficiently with less choppiness. In most cases, this buffer is 4Kb, or 4096 bytes.

    What str_pad('',4096) does is write 4,096 spaces to the output. Since it's HTML, these spaces collapse into a single space.

    Overall, this behaviour should NOT be relied upon. Browsers are for viewing webpages, not bastardising into console terminals.

    Also, why are you writing </br>? There is no such thing as an end <br> tag, and the self-closing version is <br />