Session timeouts in PHP: best practices

前端 未结 4 605
终归单人心
终归单人心 2020-11-30 18:26

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

Suppose I want the users session to be invalid af

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 19:02

    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;
    }
    

提交回复
热议问题