If you’re a PHP programmer, but you’ve never used register_shutdown_function(), you are not alone. Buried in the Function Handling Functions section of the PHP manual, this function is seldom in PHP programming books or tutorials. However it is very useful in many situations where the integrity of your data is essential.
The function register_shutdown_function() takes the name of a user-defined function as an argument, and then calls that function when the script terminates. As long as you call register_shutdown_function() at the top of your script, your function will be executed even if there is a PHP error or the script times out. The function will also be called if the script executes normally, with no errors.Â
Because of the guarantee that your shutdown function will be called, you can execute essential commands in your function and be certain of their result. Common uses include updating session variables or updating values in a database.
For example, say you have a script that loops through transactions, processing each one, and then updates a database with the total number of transactions processed. A good use of reigster_shutdown_function() would be to perform the database update of the number of transactions, because you can be assured that it will be executed. See example below:
<?php register_shutdown_function('safe_update'); $done_processing=false; $number_processed=0; while($done_processing==false) { Â //PROCESS A TRANSACTION... Â $number_processed++; } function safe_update() { Â global $number_processed; Â //UPDATE DATABASE WITH $number_processed } ?>

Great find. In adding this to my scripts, I found that you can register more than one shutdown function. They will be executed in the order they were registered. If exit() is called in shutdown function, then the script immediately exits even if there are other shutdown functions that haven’t been executed yet. I have already found this very useful. Thanks!