I am wondering if it would be possible to have a session cleanup event hook in future versions of PHP.
I imaging that it would work like this: <?php include( 'inc/my_functions_or_classes_library.inc.php' ); session_start(); function _my_session_cleaup( $_session_id ){ file_put_contents( 'log/session_clean.log', 'cleaning session up id; ' .. $_session_id ); //access session variable cart_id file_put_contents( 'log/session_clean.log', 'cleaning session cart; ' .. $_SESSION['cart_id'] ); //do something here that removes the cart from the database etc... } session_cleanup_register( ' _my_session_cleaup', $_store_includes=true, $log_to_file='log/session_clean-%Y-%m-%d.log' ); ?> As I see it, the process that cleans up old sessions in the background would find the function serialized in the session file along with some information about the environment in which the function was set. If the function was registered with $_store_includes=true, then any include files that were loaded at the time of the registration will be remembered and stored in the session file. PHP would then generate a temporary console script and run it as if in the same directory as when the registration was done. Any output would append to or open the $log_to_file path with date parameters dedeuced . It would include the files that were included when registered (if $_store_includes=true) and run the following: !#/usr/bin/php <?php //get the session file and unserialize its content and set to $_SESSION and make it global include( 'inc/my_functions_or_classes_library.inc.php' ); //found from the session file environment settings stored function _my_session_cleaup( $_session_id ){ echo 'cleaning session up id; ' . $_session_id; //access session variable cart_id echo 'cleaning session cart; ' . $_SESSION['cart_id']; //do something here that removes the cart from the database etc... } _my_session_cleaup( SESSION_ID_BEING_CLEANEDUP ); ?> Once completed, the session cleanup would destroy the session file.