There are times when you want to run a PHP script in the background, something that is triggered by a user, but you don’t want them to have to wait for it to complete. A couple ways to accomplish this, but I’ll focus on one in particular. That’s making an asynchronous call using AJAX.
It’s pretty simple actually. The first thing is in your script that you want to run in the background, you need to make sure it runs long enough to complete, and that also it won’t die when the connection is aborted. So, at the top of this PHP script, you’ll want to add these 2 lines:
ignore_user_abort(1); set_time_limit(0);
Now for how to actually get that script running in the background. We’ll be using javascript and taking advantage of the YUI library since it makes it particularly easy.
Basically, what happens is an async call is made to the script, and then the connection is aborted, so the script continues to run and the user can go on doing whatever they want. The key is you don’t want to abort the connection to fast. If it’s aborted right after it’s made the script won’t even have time to start. So, we need to give it a couple seconds before actually aborting. Here’s the javascript for this:
<script src="http://yui.yahooapis.com/2.8.0r4/build/yahoo/yahoo-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/event/event-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/connection/connection_core-min.js"></script>
<script type="text/javascript">
var spawnCallback = {
success: function(o) {
},
failure: function(o) {
},
timeout: 2000
};
function spawnProcess() {
YAHOO.util.Connect.asyncRequest('GET','url/to/script.php',spawnCallback);
}
</script>
And that’s about it. Then you just need to call the spawnProcess() function and it will trigger your designated PHP script which will run in the background until finished.


