Hi,

Does anybody knows how often the session garbage collector checks for expired session to delete them? is it possible to modify this timeframe? is it possible to call this function manually?

I am storing my sessions in a mysql database and i am using a session expiration of 5 seconds (just for testing), but after the session is expired the session record in the db table still exists. and it looks the sessions aren't expiring either because if you still have the session cookie you can keep up with the session.

(I am using a mysql session handler written by:
//@author Jon Parise <jon@php.net>, Harry Fuecks <hfuecks@phppatterns.com>
//@version 1.0 )

This is a fragment of the session handler:

//  * Performs session garbage collection based on the provided lifetime.
function mysql_session_gc($maxlifetime)
{
    global $mysql_session_handle, $mysql_session_table;

$expiry = time() - $maxlifetime;
$query = "delete from $mysql_session_table where last_active < $expiry;";

return (mysql_query($query,$mysql_session_handle) !== false);
}

/* Register the session handling functions with PHP. */
session_set_save_handler(
    'mysql_session_open',
    'mysql_session_close',
    'mysql_session_read',
    'mysql_session_write',
    'mysql_session_destroy',
    'mysql_session_gc'

    Ok, answering my own question.. I found this:

    Note that for security reasons the Debian and Ubuntu distributions of php do not call gc to remove old sessions, but instead run /etc/cron.d/php, which check the value of session.gc_maxlifetime in php.ini and delete the session files in /var/lib/php. This is all fine, but it means if you write your own session handlers you'll need to explicitly call your gc function yourself. A good place to do this is in your _close function, like this:

    <?php
    function close() {
    gc(get_cfg_var("session.gc_maxlifetime"));
    // rest of function goes here
    }
    ?>

      thanks for the info, I implemented a "manual" garbage collection that works on every session_close, but after reading your message I think it is a good idea to implement a probability too. like generating a random number and if that random number = x then do the garbage collection, this way I will have less sql queries 😃

        Write a Reply...