Name

register_shutdown_function()

Synopsis

    void register_shutdown_function ( function callback
    [, mixed param [, mixed ...]] )

The register_shutdown_function() function allows you to register with PHP a function to be run when script execution ends. Take a look at this example:

    function say_goodbye() {
            echo "Goodbye!\n";
    }

    register_shutdown_function("say_goodbye");
    echo "Hello!\n";
    That would print out the following:
    Hello!
    Goodbye!

You can call register_shutdown_function() several times passing in different functions, and PHP will call all of the functions in the order you registered them when the script ends. If any of your shutdown functions call exit, the script will terminate without running the rest of the functions.

One very helpful use for shutdown functions is to handle unexpected script termination, such as script timeout, or if you have multiple exit() calls scattered throughout your script and want to ensure that you clean up no matter what. If your script times out, you have just lost control over whatever you were doing, so you either need to back up and undo whatever you have just done, or you need to clean up and terminate cleanly. Either way, shutdown functions are perfect: register a clean-up function near the start of the script and, when script timeout happens, the clean-up function will automatically run.

For example, the following script will print out "Sleeping...Goodbye!":

 function say_goodbye() { print "Goodbye!\n"; } register_shutdown_function("say_goodbye"); ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.