92Jacko
92Jacko

Reputation: 523

Run PHP script in the background (without interrupting the user)?

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.

From what I have found, there are a few methods to achieving this, one is to launch a popen command, another is to use exec, and the last I know of is using fsockopen (source):

$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); 
}

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

Is this the best method available to me?

Thanks for any support (:

EDIT:

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

Is this solution recommended?

E.G:

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..

Upvotes: 4

Views: 1478

Answers (1)

Mike Purcell
Mike Purcell

Reputation: 19999

You could implement a queuing solution to fulfill your requirements which would work like this:

  1. User logs in
  2. PHP User function adds work to a 'login' queue
  3. An 'always-on' PHP script (worker) is assigned work from the queue
  4. Work is completed in the background

This approach is a little more advanced, in that you have to introduce a queue manager and php daemon(s) to handle the work, but it works great when completed.

I would suggest reading some docs on 'Gearman', which has built-in php user functions.

Upvotes: 1

Related Questions