0

I'm trying to run a simple PHP script on MAMP. I'm using PHP 5.2.17 and I have compression turned off. Im trying to execute this simple script

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

For sme reason this is not doing what it is supposed to. Rather than sequentially echoing out the numbers, it's simply echoing them out when the loop is done. Am I missing something? is there another way to do this?

user379468
  • 3,989
  • 10
  • 50
  • 68

2 Answers2

1

Output buffering is a mechanism for controlling how much output data (excluding headers and cookies) PHP should keep internally before pushing that data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify. Turning on this setting and managing its maximum buffer size can yield some interesting side-effects depending on your application and web server. You may be able to send headers and cookies after you've already sent output through print or echo. You also may see performance benefits if your server is emitting less packets due to buffered output versus PHP streaming the output as it gets it. On production servers, 4096 bytes is a good setting for performance reasons.

Note: Output buffering can also be controlled via Output Buffering Control functions.

php.ini Possible Values:

On = Enabled and buffer is unlimited. (Use with caution) 
Off = Disabled    
Integer = Enables the buffer and sets its maximum size in bytes.  
eg: output_buffering = Off

Note: This directive is hardcoded to Off for the CLI SAPI

http://php.net/output-buffering

A Working example if output_buffering is set to 4096

<?php
ob_start();
// Output string to overflow browser php.ini output_buffering setting.
echo str_repeat(PHP_EOL, 4097);

for ($i=0; $i<5; $i++) {
  echo PHP_EOL.$i;
  ob_flush();
  flush();
  sleep(1);
}
ob_end_flush();
?>
Community
  • 1
  • 1
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

Indeed, it is the buffer size

PHP buffer why \r\n

This example worked for me

Community
  • 1
  • 1
user379468
  • 3,989
  • 10
  • 50
  • 68