user3172633
user3172633

Reputation: 43

Why flush() not working in for loop? (PHP)

I want use flush() function in for loop that echo content after each loop
my code is:

<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
        echo "<br> Line".$i." to show.";
        ob_flush();
        flush();
        sleep(2);
}

echo "<br>Done.";

ob_end_flush();
?>

this code works on localhost and another host(Demo) but not working on my main host(Demo + phpinfo page)

how i can solve this? I use chrome

Upvotes: 0

Views: 592

Answers (3)

Roman Sevastyanov
Roman Sevastyanov

Reputation: 206

Problem in your PHP configuration.

output_buffering — is a parameter in your PHP configuration file php.ini. It enable output buffering for data.

In your PHP configuration it has 'no value'. So, just set output_buffering parameter 'On'. Or if you want set some limit for buffering data set count of bytes (for example'4096') in this directive.

Upvotes: 1

user669677
user669677

Reputation:

Try set this at the beggining:

ini_set('implicit_flush', true);

Source here

Upvotes: 0

escitalopram
escitalopram

Reputation: 3856

There's a »varnish« proxy in front of your second server. It disturbs the timing of your script. You should generally not rely on timing when returning your response, precisely because there might be a proxyserver in the way. You might want to use some sort of polling or WebSockets instead.

$ nc shoma.info 80
GET /test/1.php HTTP/1.1
Host: shoma.info
Connection: close

HTTP/1.1 200 OK
Server: Apache
X-Powered-By: PHP/5.3.28
Vary: Accept-Encoding
Content-Type: text/html
Content-Length: 209
Accept-Ranges: bytes
Date: Sat, 22 Mar 2014 19:18:40 GMT
X-Varnish: 972965439
Age: 0
Via: 1.1 varnish <------- this is the problem
Connection: close

<br> Line 0 to show.<br> Line 1 to show.<br> Line 2 to show.<br> Line 3 to show.<br> Line 4 to show.<br> Line 5 to show.<br> Line 6 to show.<br> Line 7 to show.<br> Line 8 to show.<br> Line 9 to show.<br>Done.

BTW: My firefox here doesn't even show the »animation« of your first server. So you can't even rely on the browser displaying it.

Upvotes: 1

Related Questions