How to buffer text to the client with PHP

When you look over the internet there are many people, who say it isn’t possible anymore to buffer text to the clients browser. Earlier it was possible, but not anymore. That’s not true. It’s just a bit more complicated.

At the very beginning of the file (before doctype!) you have to set the following code:

<?php
    header('Content-type: text/html; charset=utf-8');
    ini_set('zlib.output_compression',0);
    ini_set('implicit_flush',1);
    ob_end_clean();
    set_time_limit(0);
?>

And now you can use flush() every time you want to output something to the client.

An example:

<?php
    header('Content-type: text/html; charset=utf-8');
    ini_set('zlib.output_compression',0);
    ini_set('implicit_flush',1);
    ob_end_clean();
    set_time_limit(0);

    echo "Hello World<br />";
    flush();
    sleep(3);
    echo "Hello World after 3 seconds";
    flush();
?>

The client now sees Hello World and after 3 seconds Hello World after 3 seconds.

The best way is to simply write a new function that outputs a string and then instantly flushes.

For example:

<?php
    function output($text){
        echo $text;
        flush();
    }
?>
Written on February 27, 2022