Search code examples
phploopswhile-loopdo-whileabort

Why does echo not work in a do while loop or even when ignore_user_abort(1)?


I used a log printer to test to see if the ignore_user_abort works, it does. However the echo does not want to work. Will an echo only work when a loop compleates?

<?php
ignore_user_abort(1); // run script in background 
set_time_limit(0); // run script forever 
$interval=2; // do every 2 sec... 
$i=0;
 $lastRunLog = 'lastrun.log';
do{ 
   // add the script that has to be ran every 2 sec here 
   // ... 
   echo 'Test: '.$i;

   file_put_contents($lastRunLog, time());


   sleep($interval); // wait 2 sec 
   $i=$i+1;
}while(true); 
?>

Solution

  • Yes, and no.

    There are three output buffers you need to worry about:

    1. PHP can buffer output. You can use the ob_ functions to control that buffer and force output to apache/iis (the web server)
    2. Apache/IIS have their own buffers, and will only send information when they think they have enough to send. This is also compunded by mod_gzip or other compression. You can't control this through PHP.
    3. There are also potentially other caches/proxies between your browser and the server. These MAY hold up output until it receives a full response.

    So, echo puts into the PHP buffer immediately. You can send the buffer to teh webserver, but after that it's out of your hands.