5

Is it possible to display string on the browser while in infinite loop? This is what I want to happen:

while(1) {
     echo "should display these lines on browser while in infinite loop.<br>";
}
Neigyl R. Noval
  • 6,018
  • 4
  • 27
  • 45
  • 1
    0_0 Why would you purposefully enter an infinite loop without any break point? Without testing this, I suspect that it'll just cause a server-side overflow and die, showing nothing client-side. –  Aug 29 '11 at 16:34
  • 2
    What exactly are you trying to accomplish? PHP doesn't output to the browser until it's done executing, usually. You can try to add `flush();` after the `echo`. – gen_Eric Aug 29 '11 at 16:35
  • 2
    I really hope this is a HUGELY simplified example. – Madara's Ghost Aug 29 '11 at 16:35
  • I wanted to know if it is possible. I tried the code but for 50 lines and the display is shown after the loop. How is this possible in infinite loops? Or am I missing something or not possible at all? – Neigyl R. Noval Aug 29 '11 at 16:36
  • how is 50 lines NEARLY enough for you to notice whether it's immidiate or after the loop finishes? – Madara's Ghost Aug 29 '11 at 16:38
  • 1
    Why do you have an infinite loop? Do you have a condition to break the loop? – gen_Eric Aug 29 '11 at 16:39

4 Answers4

14

Yes, it is possible. You need to flush the output to the browser if you want it to appear immediately:

while(1) {
     echo "should display these lines on browser while in infinite loop.<br>";
     flush();
}

Chances are that whatever you're trying to accomplish, this isn't how you should go about it.

PHP will eventually time-out, but not before it generates a massive HTML document that your browser will have trouble displaying.

user229044
  • 232,980
  • 40
  • 330
  • 338
6

Notice the use of ob_flush(); to make sure php outputs, and usleep(100000) to have time to see things happening.

while(1) {
     echo "should display these lines on browser while in infinite loop.<br>";
     usleep(100000); // debuging purpose
     ob_flush();
     flush();
}
Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
2

Add flush() after the echo statement, it will flush the output to the browser. Note that browsers generally don't start to render until their reach a certain amount of information (around .5kB).

while(1) {
     echo "should display these lines on browser while in infinite loop.<br>";
     flush(); //Flush the output buffer
}
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

If you don't want to put flush(); after each echo of your code:

Set this in your php.ini:

implicit_flush = Off

Or if you don't have access to php.ini:

@ini_set('implicit_flush',1);

Tarik
  • 4,270
  • 38
  • 35