PHP flushing output as soon as you call echo

前端 未结 6 727
有刺的猬
有刺的猬 2020-12-22 08:47

I thought flush(); would work, at least from what Google/Stackoverflow tell me, but on my Windows WAMP (Windows, Apache, MySQL, PHP) system it doesn\'t work.

相关标签:
6条回答
  • 2020-12-22 09:17

    If you're using CGI/FastCGI, forget it! These don't implement flush. The Webserver might have it's own buffer.

    You can disable all output buffering in PHP with following command:

    ob_implicit_flush();
    
    0 讨论(0)
  • 2020-12-22 09:17

    Maybe the problem is Apache here, which also may have buffers...

    0 讨论(0)
  • 2020-12-22 09:29

    The script works fine from CLI, displaying "Fun", waiting 5 secs before displaying "<br>Mo".

    For a browser the results might be a bit different because:

    1. The browser wont start rendering right away. Getting 3 bytes of data for HTML document isn't enough to do anything, so it'll most likely wait for a few more.
    2. Implicit IO buffering on the lib level will most likely be active until a newline is received.

    To work around 1) use text/plain content type for your test; 2) needs newlines, so do an echo "Fun\n"; and echo "<br>Mo\n"; Of course you wont be using text/plain for real HTML data.

    0 讨论(0)
  • 2020-12-22 09:29

    So that's what I found out:

    Flush would not work under Apache's mod_gzip or Nginx's gzip because, logically, it is gzipping the content, and to do that it must buffer content to gzip it. Any sort of web server gzipping would affect this. In short, at the server side, we need to disable gzip and decrease the fastcgi buffer size. So:

    • In php.ini:

      . output_buffering = Off

      . zlib.output_compression = Off

    • In nginx.conf:

      . gzip off;

      . proxy_buffering off;

    Also have this lines at hand, specially if you don't have acces to php.ini:

    • @ini_set('zlib.output_compression',0);

    • @ini_set('implicit_flush',1);

    • @ob_end_clean();

    • set_time_limit(0);

    Last, if you have it, coment the code bellow:

    • ob_start('ob_gzhandler');

    • ob_flush();

    PHP test code:

    ob_implicit_flush(1);
    
    for($i=0; $i<10; $i++){
        echo $i;
    
        //this is for the buffer achieve the minimum size in order to flush data
        echo str_repeat(' ',1024*64);
    
        sleep(1);
    }
    
    0 讨论(0)
  • 2020-12-22 09:34

    If the problem persists, although you explicitly set

    implicit_flush = yes 
    

    in your php.ini, you might also want to set

    output_buffering = off
    

    which did the trick in my case (after pulling my hair for 4+hrs)

    0 讨论(0)
  • 2020-12-22 09:36

    Check your php.ini for output_buffering.

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