PHP shutdown sequence

I needed to figure out in what order PHP shuts down, after the end of a script has been reached, so I created a small testing script. Maybe this is of use for someone else trying to google this like I tried.

  1. <?php
  2.  
  3.     // Testing shutdown sequence
  4.  
  5.     function shutdown() {
  6.  
  7.         echo "register_shutdown_function\n";
  8.  
  9.     }
  10.  
  11.     register_shutdown_function('shutdown');
  12.  
  13.  
  14.     class MyClass {
  15.  
  16.         function __destruct() {
  17.  
  18.            echo "Object destructor\n";
  19.  
  20.         }
  21.  
  22.  
  23.     }
  24.  
  25.     function obcallback($buffer) {
  26.  
  27.         $buffer .= "Output buffer callback\n";
  28.         return $buffer;
  29.  
  30.     }
  31.  
  32.     ob_start('obcallback');
  33.  
  34.     $myObject = new MyClass;
  35.  
  36.     function dummy() { }
  37.  
  38.     function sessionclose() {
  39.  
  40.         echo "Session close\n";
  41.  
  42.     }
  43.  
  44.     function sessionwrite() {
  45.  
  46.         echo "Session write\n";
  47.     }
  48.  
  49.     session_set_save_handler('dummy','sessionclose','dummy','sessionwrite','dummy','dummy');
  50.  
  51.     session_start();
  52.  
  53. ?>

The output, on PHP 5.2.0 on the cli is:

  1. register_shutdown_function
  2. Object destructor
  3. Output buffer callback
  4. Session write
  5. Session close

I was mostly interested in this because I wanted to work with a custom session handler. This means I can basically not use objects in combination with session handlers, unless I don't rely on $this.


6 Responses to PHP shutdown sequence

  1. 457 Richard Thomas 2007-11-05 5:32 pm

    Yes you can, you need to register session_close in your register_shutdown_function

    Or

    register_shutdown_function("session_write_close");

    This closes the session up prior to the objects being destroyed

  2. 458 Evert 2007-11-05 5:58 pm

    Thats smart!

  3. 455 Johannes 2007-11-06 5:36 pm

    That part of the PHP code is een good commented, so you can et the real order without much internals&C knowledge: http://lxr.php.net/source/php-src/main/main.c#1546

  4. 456 Evert 2007-11-06 6:12 pm

    That is pretty cool.. looks like I haven't really missed anything =)

  5. 460 Adam 2007-11-12 11:18 pm

    I always love investigative PHPing. Good work and very useful!

  6. 459 open source 2007-12-22 5:13 pm

    I think it is a tip of the day :)

Leave a Reply



About

My name is Evert, and I've been writing semi-regularly on this blog since 2006.

I'm currently available for contract work.

more info.

Subscribe

Dropbox

Dropbox is a simple cross-platform online backup and sync application. The first 2GB of space is free, and both you and me get an extra 250MB extra space if you sign up through this link.