phpsecuritycookiessession-timeout

Session timeouts in PHP: best practices


What is the actual difference between session.gc_maxlifetime and session_cache_expire() ?

Suppose I want the users session to be invalid after 15 minutes of non-activity (and not 15 after it was first opened). Which one of these will help me there?

I also know I can do session_set_cookie_params() which can set the user's cookie to expire in some amount of time. However, the cookie expiring and the actual session expiring on the server side are not the same; does this also delete the session when the cookie has expired?

Another solution I have though of is simple $_SESSION['last_time'] = time() on every request, and comparing the session to the current time, deleting the session based on that. I was hoping there was a more "built-in" mechanism for handling this though.

Thanks.


Solution

  • Each time session_start is called the session files timestamp (if it exists) gets updated, which is used to calculated if session.gc_maxlifetime has been exceeded.

    More importantly you can't depend on a session to expire after session.gc_maxlifetime time has been exceeded.

    PHP runs garbage collection on expired sessions after the current session is loaded and by using session.gc_probability and session.gc_divisor it calculates the probability that garbage collection will run. By default its a 1% probability.

    If you have a low number of visitors there is a probability that an inactive user could access a session that should have expired and been deleted. If this is important to you will need to store a timestamp in the session and calculate how log a user has been inactive.

    This example replaces session_start and enforces a timeout:

    function my_session_start($timeout = 1440) {
        ini_set('session.gc_maxlifetime', $timeout);
        session_start();
    
        if (isset($_SESSION['timeout_idle']) && $_SESSION['timeout_idle'] < time()) {
            session_destroy();
            session_start();
            session_regenerate_id();
            $_SESSION = array();
        }
    
        $_SESSION['timeout_idle'] = time() + $timeout;
    }