Sunday, October 4, 2009

timeout in Session (PHP)



  • Sessions allow the PHP script to store data on the web server that can be later used, even between requests to different php pages.


  • When a session is created, a flat-file is created on the server. Since the session ID is a unique identifier, those session files will accumulate over time.


  • The PHP garbage collector deletes old files from time to time. But the garbage collector is invoked with a certain probability, not every time the web server runs.


  • The default timeout for session files is 1440 seconds or 24 minutes. So a session file can be deleted after that timeout, but it may reside on the server longer, depending on the amount of sessions created - here comes the probability into the game.


  • The session may reside in server with a lifetime until the browser is closed, but the garbage collector might delete the session file much earlier. In this case, and if there is a session request after the session file has been deleted, a new session is created and the old session information is lost. This is annoying.


  • There are 3 variables described in PHP.ini file, which deal with the garbage collector





    Variabledefault valueChangeable
    session.gc_maxlifetime1440 secondsPHP_INI_ALL
    session.gc_probability1PHP_INI_ALL
    session.gc_divisor100PHP_INI_ALL

    session.gc_probability along with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is invoked. The probability is calculated by using gc_probability/gc_divisor.


  • The garbage collection timeout can be changed.

    $timeout = 7200; // 7200 seconds = 2 hour
    ini_set('session.gc_maxlifetime', $timeout);




  • Session timeout can be reduced without changing the global variable programmatically .

    session_start();
    // set timeout period in seconds
    $inactive = 600;
    if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive) {
    session_destroy(); header("Location: logoutpage.php"); }
    }
    $_SESSION['timeout'] = time();




1 comment: