PHP - How to register a shutdown / cleanup function to be run at the end of the script?

There is a function called register_shutdown_function(), which will let you execute some code right before the script finishes running.

At first this may seem trivial. You just add the code to the very bottom of the script and it runs before it finishes. However, if you ever call the exit() function, that code will never run. Also, if there is a fatal error, or if the script is terminated by the user (by pressing the Stop button in the browser), again it may not run.

When you use register_shutdown_function(), your code will execute no matter why the script has stopped running.

$start_time = microtime(true);
register_shutdown_function('my_shutdown');
// do some stuff
// ...
function my_shutdown() {
    global $start_time;
    echo "execution took: ".
            (microtime(true) - $start_time).
            " seconds.";
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License