6

I need a fix for this.
here is just part of my code

<?php
$number = 30;
while($number > 0) {
 $number--;
 sleep(30);
 print "$number . Posted<br>";

}
?> 

The loop process in the loop is actually much bigger, i just put the important stuff.

Anyways as you can see it should print
30 posted
(wait 30 seconds)
29 Posted
(wait 30 seconds)
28 Posted
(wait 30 seconds)

But instead it waits till the loop is over, then just prints it all at once. Is there a fix for this? I was thinking an ajax method, but I dont know of any.

5 Answers 5

17

Nice that everyone explained why.

This is because by default PHP will process everything before it 'flushed' anything out to the browser. By just printing each line, it's storing that information in the buffer which will all be printed simultaneously once PHP is finished executing.

If you want PHP to flush that content to the browser immediately after the line, you need to call flush() after each one, then it will output the text one line at a time after each one is called.

Sign up to request clarification or add additional context in comments.

Comments

4

Call flush() after printing.

Comments

2

You need to use flush()

Comments

1

An example of a loop with flush() is

<?php
 ob_start();
 for ($i = 0; $i < 10; $i++)
 {
   echo "<div>" . time() . ": Iteration $i</div>";
   sleep(1);
   ob_flush();
   flush();
 } 
 ob_end_flush();
?>

You should not flush often because you force php to process messages and this will increase the time of execution.

Comments

0

You might put \n in echo or print to flush the buffer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.