How to Use ignore_user_abort() to Do Processing Out of Band
Ever wanted to process things out of band in your php scripts? The ignore_user_abort() function allows you just to do that.
int ignore_user_abort ( [bool $setting] )
Sets whether a client disconnect should cause a script to be aborted.
If not set, the function will only return the current setting.
Basically, when you use ignore_user_abort(true) in your php script, the script will continue running even if the user pressed the esc or stop on his browser. How do you use this? One use would be to return content to the user and allow the connection to be closed while processing things that don’t require user interaction.
The following example sends out $response to the user, closing the connection (making the browser’s spinner/loading bar stop), and then executes do_function_that_takes_five_mins();
ignore_user_abort(true); header("Connection: close"); header("Content-Length: " . mb_strlen($response)); echo $response; flush(); do_function_that_takes_five_mins();
It’s that easy! You can also redirect the user in the same fashion. In the example below I’ve added the line session_write_close() which forces the session to be written. If this is not done, any modifications to $_SESSION will not take affect to user’s other sessions until do_function_that_takes_five_mins(); has finished.
ignore_user_abort(true); session_write_close(); // optional, this will close the session. header("Location: $redirect_url"); flush(); do_function_that_takes_five_mins();
Also, if your max execution time is set to something low, you can increase the time limit for scripts by using set_time_limit(). Just keep in mind, the php process will still take up an apache process until it’s completed. This is a great technique to give the user immediate response and speed up your web apps!