PHP Flush that works… even in Nginx

前端 未结 8 829
既然无缘
既然无缘 2020-11-30 22:29

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

相关标签:
8条回答
  • 2020-11-30 23:22

    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

    0 讨论(0)
  • 2020-11-30 23:22

    You can accomplish this by flushing the output buffer in the middle of the loop.

    Example:

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

    Note that your php.ini settings can affect whether this will work or not if you have zlib compression turned on

    0 讨论(0)
提交回复
热议问题