doutuo1908 2016-02-08 16:38
浏览 55

从数据库清除过期的会话[关闭]

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?

  • 写回答

1条回答 默认 最新

  • duai5344 2016-02-08 16:46
    关注

    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

    评论

报告相同问题?