Tuesday, November 6, 2012

PHP's register_shutdown_function

PHP has approx. 5800 functions defined in global space .. Uff .. that is one cause that people does not consider it as thoughtful language but these APIs work as strong enough tool to accomplish various task and it provide tremendous functionality to end user.


Today we will discuss one magical function named "register_shutdown_function".

function allows you to execute a block of code whenever your script ends for any reason.
Whether your page exit()s or die()s or just finishes, a developer has a hook to run whatever code he/she deems necessary. And not just one function either… you can use this call to register as many shutdown functions as you want, and they will get executed in the order that they get applied. But of course, you must be careful: PHP will happily give you more rope than you will ever need to hang yourself. A lot of people may consider the use of this function to be magic, and you’ll want to be very clear that what you’re doing is documented.


Use of this function is very straight-forward.

I just tested with Apache, PHP being used as Apache module. I created an endless loop like this:

class X
{
    function __destruct()
    {
        $fp = fopen("/var/www/dtor.txt", "w+");
        fputs($fp, "Destroyed\n");
        fclose($fp);
    }
};

$obj = new X();
while (true) {
    // do nothing
}

Here's what I found out:-


  1. pressing STOP button in Firefox does not stop this script
  2. If I shut down Apache, destructor does not get called
  3. It stops when it reaches PHP max_execution_time and destuctor does not get called

However, doing this:

function shutdown_func() {
    $fp = fopen("/var/www/htdocs/dtor.txt", "w+");
    fputs($fp, "Destroyed2\n");
    fclose($fp);
}

register_shutdown_function("shutdown_func");

while (true) {
    // do nothing
}

shutdown_func gets called. So this means that class destuctor is not that good as shutdown functions. :-)

Enjoy !! :-)




1 comment: