Useful PHP Function: register_shutdown_function()

Since i’ve started programming in PHP i’ve found that there are some very interesting and useful functions native to the language that are buried deep in the very extensive PHP documentation. Sometimes you want to do something with your code and you end up writing lines and lines of elaborate code only to find out maybe a few months later that there is a function built into PHP that does exactly what you wanted to and does it a zillion times better. This can happen to almost any PHP developer, regardless of their level of experience. Even if you study every word on every page of the PHP docs it is very unlikely that you will remember it all. Sometimes you consult the manual searching for a solution but you either don’t know where to look or, more likely, you really don’t have the time to look. I’ve decided then that at least once a week i’ll write on my blog about a native PHP function that i’ve discovered and found to be very useful. Without further ado, the function for this week is register_shutdown_function().


While investigating an issue with my WordPress plugin GeoSmart, I traced the source of the problem to another plugin that was appending an html comment to the end of some JSON data that being retrieved via ajax by my plugin thereby rendering the JSON string invalid. After trying in vain to find a workaround to the problem, I decided to dig into the code of the offending plugin. It was there that I found the function register_shutdown_function().

According to the PHP manual, the function register_shutdown_function() registers a function for execution when the script processing is complete (i.e. upon script termination). It takes as parameters, the name of the function to be executed and optionally, any arguments to be passed to that function. You can register more than one function to be executed on script termination and they are executed in the order that they are registered. However, if exit() is called in any of the registered functions, any functions registered after it will not be called. Example:

function addCredits()
echo 'Script author: Samuel Folkes';

I can think of quite a few uses for this function. You could for example define a clean up function to run after your script has finished processing that would remove any temporary files your script may have created. Alternatively, you could use it to register a function that would force a particular output at the end of your script execution like in the example above. I’m sure you’ll be able to find even more creative uses for this very useful function.

« (Previous News)

Comments are Closed