Neigyl R. Noval
Neigyl R. Noval

Reputation: 6038

Display the output while looping in php

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>";
}

Upvotes: 5

Views: 12436

Answers (4)

Tarik
Tarik

Reputation: 4536

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);

Upvotes: 0

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41855

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();
}

Upvotes: 6

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

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
}

Upvotes: 2

user229044
user229044

Reputation: 239240

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.

Upvotes: 14

Related Questions