PHP Flush that works... even in Nginx

Roger picture Roger · Feb 2, 2011 · Viewed 26.7k times · Source

Is it possible to echo each time the loop is executed? For example:

foreach(range(1,9) as $n){
    echo $n."\n";
    sleep(1);
}

Instead of printing everything when the loop is finished, I'd like to see it printing each result per time.

Answer

Andy Fowler picture Andy Fowler · Apr 19, 2014

The easiest way to eliminate nginx's buffering is by emitting a header:

header('X-Accel-Buffering: no');

This eliminates both proxy_buffering and (if you have nginx >= 1.5.6), fastcgi_buffering. The fastcgi bit is crucial if you're using php-fpm. The header is also far more convenient to do on an as-needed basis.

Docs on X-Accel-Buffering Docs on fastcgi_buffering