Thursday, August 22, 2013

Asynchronous cURL Requests

A possibly underused technique available to PHP developers is the ability to spawn a background PHP script without JavaScript. All you need to do this is the cURL library and a few lines of code. Let me explain, suppose you have a script that is going to take minutes (or longer) to run, you don’t want to sit looking at a blank screen, and your users certainly won’t! In this kind of scenario you can separate out that logic to a background file and leave your view free for other things, perhaps to query the database to see how the background process is doing?
All you need to do to set this off is use the following code (entering your own url):
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_NOBODY, true); 

curl_exec($ch);
curl_close($ch);
There is an irritating 1 second delay for this to finish, but this cannot be helped (so far as I am aware!)
Remember to be careful with this technique (especially if you turn off script timeout etc) and build in a control to stop the script should you need to (database query every minute? or a lock file?)
Enjoy!

Update

It has been pointed out to me that on modern systems (cURL 7.16.2 or higher and PHP 5.2.3 or above) you can use a millisecond option to reduce the delay effectively to zero.
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_setopt($ch, CURLOPT_NOBODY, true);

curl_exec($ch);
curl_close($ch);

No comments:

Post a Comment