DEV Community

Aaron Junker
Aaron Junker

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

2 2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay