title: PHP, Apache. Output response to browser before script has finished
body: <p>I have a script that pulls users from the DB, prepares an XMPP message, loops through each user and sends the XMPP message, then logs that the message was sent. Easily running through 1000 users plus. This is a server side API script that is called from a mobile device. The mobile device is waiting to receive a success JSON response. The user experience should be quick, I don't want the mobile user waiting for more than a few seconds for the response.</p>
  
  <p>Problem is its taking a fair amount of time for the script to loop through all users, so my initial solution was to use ob_flush() - note these are merely test scripts to see if the planned method works:</p>
  
  <pre><code>    ob_start(); 
  
  $profiles_ar = array(
      "reach" =&gt; 30,
  );
  
  $return_ar = array(
      "success"   =&gt; $profiles_ar['reach'],
  );
  
  echo json_encode($return_ar);
  
  $buffer = str_repeat(" ", 4096);                    // Note apparently  the buffer must be "filled" with 4096 characters (bytes?) for ob_flush() to work before sleep() occurs.
  
  echo $buffer;
  
  ob_flush();
  
  flush();
  
  for($i=0;$i &lt; $profiles_ar['reach']; $i++)
  {
     sleep(1);
  }
  
  echo "finshed: ".$i;
  
  ob_flush();
  
  flush();
  </code></pre>
  
  <p>That's not working, nothing gets output until the script has finished - have I missed something with OB technique?</p>
  
  <p>...... so did some searching and came up with this:</p>
  
  <pre><code>register_shutdown_function('process_after');
  
  $profiles_ar = array(
      "reach" =&gt; 10,
  );
  
  $return_ar = array(
      "success"   =&gt; $profiles_ar['reach'],
  );
  
  echo json_encode($return_ar);
  
  
  echo $buffer;
  
  exit;
  
  function process_after()
  {
      global $profiles_ar;
  
      for($i=0;$i &lt; $profiles_ar['reach']; $i++)
      {
         sleep(1);
      }
  
      echo "finshed: ".$i;
  }
  </code></pre>
  
  <p>this one works on mac, but not on the server.... </p>
  
  <p>Anyone got any ideas? If i cant get this technique of outputting the response JSON before the main processing to work, then my only hope is to build a queue in the DB and run a cron job........ ;(</p>