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?
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.
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.
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.
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.
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";
}
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With