This is a question I have:
How to update the page on browser(chrome,firefox) when a loop is load, for example:
<?php
$var = 0;
while($var != 10){
echo $var;
$var++;
sleep(1);
}
?>
The page dont update, only after the execution of php script is finish, Anything can help me ? Thanks.
You can do it like this:
<?php
if (ob_get_level() == 0) ob_start();
for ($var = 0; $var <= 10; $var++) {
echo $var;
ob_flush();
flush(); // echo output buffer to client
sleep(1);
}
ob_end_flush();
?>
To make this work you should have disabled output compression in PHP settings like this:
zlib.output_compression = Off
or try to disable it in code (if allowed):
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
This is basically impossible.
PHP uses its own output buffering (php://output
) inside it's engine. That buffer gets filled up with data that you echo in your code. Once the engine hits the end of your script(s), it will flush the whole buffer and append it to the header information that the webserver started to create (imagine it as the webserver being the one who prepaired the response to the browser and PHP being the one to add the actual content).
Another limitation is that some browsers wait until the whole HTTP request is done and then start rendering a site. Not all do that, but some.
For real live action, I would recommend either AJAX or the more modern WebSockets. The second is even more live as it will not reload perodically like AJAX does. I suggest you to re-think what you are trying to do, and if its neccessary.
Some Wikipedia articles I'd suggest you to look at if you didn't understand anything: