2

I'm trying to execute a PHP script which during execution provides the current status/percentage of completed actions. For do that I call the script with AJAX and I use the ob_flush for send the output to the client during script execution, it worked on Apache but now I'm porting the project on Nginx and I need compatibility for both. On Nginx I use PHP-FPM for handle PHP files, here's the test script which I'm trying to run correctly:

//SET CORRECT CONTENT-TYPE (THEY WILL BE JSON STRINGS SEPARED BY BREAKLINE)
header('Content-type: text/plain; charset=utf-8');
//DISABLE GZIP FOR THE SCRIPT
ini_set('zlib.output_compression', 'Off');
ini_set('output_buffering', 'Off');
ini_set('output_handler', '');

ob_end_clean();
set_time_limit(0);

for ( $i = 0 ; $i < 5 ; $i++ ){
    echo "{\"code\":" . $i . "}\n";
    //SEND OUTPUT TO CLIENT
    flush();
    ob_flush();
    sleep(1);
}

The problem is that when I run this I get the output just when the script ends the execution, so after about 5 seconds. Someone can tell me what I'm doing wrong?

2
  • Take a look here - serverfault.com/q/488767 Commented Aug 13, 2016 at 19:40
  • For now I've resolved overloading the buffer by adding some extra spaces to the message using the function str_repeat(' ', 4096 * 8), it's a very inefficient and inelegant way to use flushing but it appears to be the only one with NGINX, anyway I have to give a look to the fastcgi_keep_conn on;" directive in the server configuration block in NGINX configuration file, maybe it can allows me to use normal PHP flush. Commented Aug 20, 2016 at 10:39

1 Answer 1

6

You should set HTTP response header 'X-Accel-Buffering' to 'no' when you don't want the Nginx to buffer the response from FastCGI server.

http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_buffering

Sign up to request clarification or add additional context in comments.

1 Comment

Calling header('X-Accel-Buffering: no'); in php script, or setting fastcgi_buffering: off; to turn off buffers globally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.