PHP Flush/ob_flush not working

JakeSmith picture JakeSmith · Dec 19, 2010 · Viewed 33.7k times · Source

I've tried several attempts at getting my flush and ob_flush to work. I've tried setting the ini to allow buffering, I've tried using several different functions I found online for output buffering, and none of it at all is working. The script wants to wait until it is completly done until it echos output. Here is the script I have so far

 ob_start();

 //Login User
 echo 'Logging in to user<br>';
       ob_flush();
       flush();
      $ch = curl_init("http://www.mysite.com/login/");
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, "username=$user&pass=$pass");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies/$cookie");
      curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies/$cookie");
      $output = curl_exec($ch);
      curl_close($ch);
      ob_flush();
      flush();

       //Update Status
 echo 'Updating Status<br>';
       ob_flush();
       flush();
      $ch = curl_init("http://www.mysite.com/update/");
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, "status=$status");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies/$cookie");
      curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies/$cookie");
      $output = curl_exec($ch);
      curl_close($ch);
      ob_flush();
      flush();

I want it to echo what it is doing, then run the function, then echo something else, then do another function. I want all the buffers to be flushed and echoed in real time on the browser.

Answer

netcoder picture netcoder · Dec 19, 2010

The idea here is to disable output buffering, not enable it. As its name says, output buffering will save the output to memory and display it at the end of the script, or when explicitly asked for it.

That being said, you don't have to flush explicitly for every output. Use the following, before displaying any output, and then you won't have to bother flushing every time you echo something:

ob_implicit_flush(true);
ob_end_flush();

Per example:

ob_implicit_flush(true);
ob_end_flush();

for ($i=0; $i<5; $i++) {
   echo $i.'<br>';
   sleep(1);
}

Will output, 0 to 4, with each being displayed every second.