DEV Community

Aaron Junker
Aaron Junker

Posted on • Originally published at blog.aaron-junker.ch

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);
?>
Enter fullscreen mode Exit fullscreen mode

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();
?>
Enter fullscreen mode Exit fullscreen mode

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();
    }
?>
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)