Tanvi Malhotra February 2016

Cleaning expired session from database

I am currently storing my sessions inside my mysql database however i see a lot of sessions whose date of expiry has reached .Now i don't have any other kind of script running for collecting up expired sessions however i read about garbage collection but there is a less chance that garbage collection will take care of large amount of expired sessions as soon as they expire.

I am looking forward for a script or alternative solution which automatically deletes expired sessions?

Answers


Gavriel February 2016

You'll have to implement your session handler class, and it's gc function can delete old session data:

function gc($lifetime) {
    $db = new PDO("mysql:host=myhost;dbname=mydb", "myuser", "mypassword");

    $sql = "DELETE FROM session WHERE session_lastaccesstime < DATE_SUB(NOW(), INTERVAL " . $lifetime . " SECOND)";
    $db->query($sql);
}

Garbage collection is performed on a random basis by PHP. The probability that garbage collection is invoked is decided through the php.ini directives session.gc_probability and session.gc_divisor. If the probability is set to 1 and the divisor is set to 100 for example, the garbage collector has a 1% chance of being run on each request (1/100).

You need to set gc to be the handler:

session_set_save_handler(array($sessionHandler,"open"),
                        array($sessionHandler,"close"),
                        array($sessionHandler,"read"),
                        array($sessionHandler,"write"),
                        array($sessionHandler,"destroy"),
                        array($sessionHandler,"gc"));

See more about how to use it:

http://php.net/manual/en/function.session-set-save-handler.php

Post Status

Asked in February 2016
Viewed 2,246 times
Voted 9
Answered 1 times

Search




Leave an answer