Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

PHP:

header('Content-type: text/plain');

for ($i=0; $i<10; $i++){
  echo "$i\r\n";
  ob_flush();
  flush();
  sleep(1);
}

I tried script above on 2 different servers. Both respond numbers 0...9 in every line. In case of first server each number is received every second. In case of second server there is no output for 10 seconds and entire output is displayed at once. What might be wrong int second case? I tried various uutput control Functions but it didn't help.

Set of response headers in both cases is pretty much the same:

HTTP/1.1 200 OK
Date: Mon, 03 Jan 2011 19:21:21 GMT
Server: Apache
X-Powered-By: PHP/5.2.14
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/plain
share|improve this question
    
doesn't php output to apache for the actual delivery of any data? if so, this might be an apache buffer issue (one way to check is to run the script from cmd line on each server and see if you get the same issue) –  Patrick Jan 3 '11 at 19:52
    
What about the platform / OS of each server? Are they identical? –  Khaled Jan 3 '11 at 20:38
    
which browser were you using? I know safari has a certain byte limit that it will wait to receive before flushing, despite anything you do in php –  DTest Jan 3 '11 at 21:00
add comment

3 Answers 3

You need to turn output_buffering to "Off" in php.ini and restart apache, the default for output_buffering is 4096, which prevents your ob_flush() and flush() from taking effect. You are also missing an ob_start(); at the beginning of your example code.

output_buffering = Off

share|improve this answer
add comment

Output buffering can be called at runtime or enabled by default (as in the case of your second server).

Run <?php var_dump( ini_get('output_buffering') ); ?> or <?php phpinfo(); ?> to see whether it's enabled on the server you're using.

Ref: PHP manual

share|improve this answer
add comment

When PHP flushes it buffers has little to do with when the webserver decides to write output - and the webserver may push partial responses (relatively uncommon) or, as in your case, chunked responses. Webservers do not provide the facility for direct control over the output stream. Nor should they. Using output buffering in PHP just defers chunking slightly.

If you ever want to produce output at the browser while code is still running, this is not the way to do it - fork a seperate process (preferably in a new session group) and write a stub response to the browser - then send updates to the stub using Ajax (optionally with long polling).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.