Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo 'string' while every long loop iteration (flush() not working)

Tags:

php

I have a loop that takes very long to execute, and I want the script to display something whenever the loop iteration is done.

echo "Hello!";

flush();

for($i = 0; $i < 10; $i ++) {
    echo $i;
    //5-10 sec execution time
    flush();
}

This does not display the echos until the entire script is completed. What went wrong?

like image 631
Nyxynyxx Avatar asked Jul 02 '11 11:07

Nyxynyxx


People also ask

What is flush () PHP?

The flush() function requests the server to send its currently buffered output to the browser. The server configuration may not always allow this to happen.

How to stop infinite while loop in PHP?

Since to exit the loop, you will need to make the condition in the while loop evaluate to false , you will have to set $loopCond to false . But this variable reassignment should be done inside of the while loop.

When use while loop in PHP?

PHP while loop can be used to traverse set of code like for loop. The while loop executes a block of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the body of loop. It should be used if the number of iterations is not known.

What is a for loop PHP?

PHP for loop can be used to traverse set of code for the specified number of times. It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how many times you want to execute a block of code.


2 Answers

From PHP Manual:

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

echo "Hello!";
flush();
ob_flush();

for($i = 0; $i < 10; $i ++) {
    echo $i;
    //5-10 sec execution time
    flush();
    ob_flush();
}

-or- you can flush and turn off Buffering

<?php
//Flush (send) the output buffer and turn off output buffering
while (ob_get_level() > 0)
    ob_end_flush();

echo "Hello!";

for($i = 0; $i < 10; $i ++) {
    echo $i . "\r\n";
}

?>
like image 129
Gregory Burns Avatar answered Nov 06 '22 01:11

Gregory Burns


try this

while (@ob_end_flush());      
ob_implicit_flush(true);

echo "first line visible to the browser";
echo str_pad("",1024," ");
echo "<br />";

sleep(5);

echo "second line visible to the browser after 5 secs";

Just notice that this way you're actually disabling the output buffer for your current script. So if you're trying to 'ob_end_flush()' after that you'll get a warning that there is no buffer to close.

like image 4
Grigoreas P. Avatar answered Nov 06 '22 03:11

Grigoreas P.