0

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.

Matheus.M.
  • 67
  • 1
  • 7
  • 9
    php runs on the server - if you need things to be "live" inside the browser window you need to use something that runs in the browser (eg Javascript). – Floris Dec 14 '13 at 00:16
  • 2
    Why on earth would you use `sleep()` there? – randak Dec 14 '13 at 00:19
  • @randak maybe just for fun.. i have done this too.. like for testing longpolling.. – Hardy Dec 14 '13 at 00:23
  • You may find a solution at http://stackoverflow.com/questions/4481235/php-flush-ob-flush-not-working - there are some tricks to flush the output. – Floris Dec 14 '13 at 00:30

2 Answers2

1

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'); 
Hardy
  • 5,590
  • 2
  • 18
  • 27
  • Missing a `{`. Just tested this on http://www.floris.us/SO/liveEcho.php - doesn't seem to work. – Floris Dec 14 '13 at 00:26
  • Fixed the `{` but see my link. Exact copy of this code (with the `{` ) - on my browser it all shows up at once (after 10 seconds). – Floris Dec 14 '13 at 00:27
  • Yes, it depends of your server settings. – Hardy Dec 14 '13 at 00:36
  • You might want to add that information to your answer then. "The following code works when you have these server settings:" – Floris Dec 14 '13 at 00:38
0

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:

Ingwie Phoenix
  • 2,703
  • 2
  • 24
  • 33