Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP show results while running

I'm trying to display the results while PHP script is running, as example.. a really long loop, i want it to echo the results while the page is loading, I searched really a lot through this and i couldn't find the good answer, After googling i found people saying use ob_flush from this question .. but it didn't work, as well as enabling the implicit_flush from php.ini , still didn't work
it only loads when the process is finished, i tried to run a for loop like this

ob_start();

for($i=0; $i<500; $i++){
 echo "hm\n";
 ob_flush();
}

ob_end_flush(); 

and still, didn't work.. it shows them all at once

My last guess now is that it needs more PHP configurations to enable/disable some stuff,
or.. it could also be apache2 configurations ?

What are the config settings that are related to this ? settings that needs to be disabled/enabled through Apache or PHP configurations ..

P.S. : I'm sure its possible to be done using PHP alone, I saw it done on GoDaddy hosting and saw it on several websites, of them http://www.checker.freeproxy.ru/checker/index.php .. if you try to submit it will show the results normally without using ajax, the website uses PHP and Apache, there's a mystery secret behind this

like image 701
Osa Avatar asked Jan 17 '13 11:01

Osa


3 Answers

I used this way from this answer

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

or using the for loop, they both work fine, and it to make it more accurate i use ob_flush() with flush()

for($i=0; $i<5000; $i++) {
     echo "should display these lines on browser while in infinite loop.<br>";
     usleep(30000);
     ob_flush();
     flush();
}

they both work fine without ajax

like image 176
Osa Avatar answered Nov 03 '22 10:11

Osa


Check my post here: Show progress bar in php while loop

It has some sample code as well, and covers pretty much everything you need.

PS: It can't be done with PHP alone, you need to do this with AJAX + PHP (client + server side coding). This is because the response is sent to the browser only after the file is fully interpreted.

like image 20
Vlad Preda Avatar answered Nov 03 '22 10:11

Vlad Preda


You can't do this with PHP. PHP is run server side so it executes before the HTTP response is sent back to the browser.

You would need to use AJAX to achieve this.

You may also look at websockets to achieve this kind of thing.

You could also cheat and load all the data into a hidden list, and then use javascript to show the list items one by one after the page has loaded. :)

like image 2
cowls Avatar answered Nov 03 '22 10:11

cowls