Run PHP script in the background (without interrupting the user)?
<p>I would like to run a PHP script in the background for logging visitor information (after the user's page has loaded), so that it doesn't slow the user down.</p>

<p>From what I have found, there are a few methods to achieving this, one is to launch a <code>popen</code> command, another is to use <code>exec</code>, and the last <em>I know of</em> is using <code>fsockopen</code> (<a href="http://www.webmasterworld.com/php/3875021.htm" rel="nofollow">source</a>):</p>

<pre><code>$socket = fsockopen($_SERVER['HTTP_HOST'],80,$errorno,$errorstr,10); 
if($socket) { 
   $socketdata = “GET /background_script.php HTTP 1.1\r\nHost: “.$_SERVER['HTTP_HOST'].”\r\nConnection: Close\r\n\r\n”; 
   fwrite($socket,$socketdata); 
   fclose($socket); 
}
</code></pre>

<p>My server doesn't allow the use of <code>popen</code> or <code>exec</code>, so that leaves me with <code>fsockopen</code>.</p>

<p>Is this the best method available to me?</p>

<p>Thanks for any support (:</p>

<p><strong>EDIT:</strong></p>

<p>Another possible solution which I have found could be to send <code>Connection: close</code> to the browser to stop the loading on the client side, and then <code>include</code> the <code>background_script</code>.</p>

<p>Is this solution recommended?</p>

<p>E.G:</p>

<pre><code>ob_start();
echo $OUTPUT_DATA;
header("Content-Length: ".ob_get_length());
header('Connection: close');

ob_end_flush();
ob_flush();
flush();

//Do background visitor logging stuff here..
</code></pre>
