PHP session lifetime problem

后端 未结 4 387
灰色年华
灰色年华 2020-12-12 03:09

I\'m using PHP5 here. I have made a login system that check\'s the username and password against the records in the database. I want to use sessions to store the logged valu

相关标签:
4条回答
  • 2020-12-12 03:39

    Use session_set_cookie_params() to change the lifetime of the session cookie. Note that by default, it is set to 0 which means that the cookie is set until the user exits the browser. You can do this in the following way:

    /* Set to 0 if you want the session
       cookie to be set until the user closes
       the browser. Use time() + seconds
       otherwise. */
    
    session_set_cookie_params(0);
    session_start();
    

    Then check for the last activity time, updated each time someone visits a page.

    if(($_SESSION['lastActivity'] + 300) < time()) {
        // timeout, destroy the session.
        session_destroy();
        unset($_SESSION);
        die('Timeout!');
    } else {
        $_SESSION['lastActivity'] = time();
    }
    
    0 讨论(0)
  • 2020-12-12 03:44

    Sessions stay alive aslong as the user stays on your site. You will have to use cookies to set a specific timeout.

    0 讨论(0)
  • 2020-12-12 03:47

    You can change the configuration setting session.cookie_lifetime, e.g. in php.ini or a .htaccess file:

    session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0.

    This means (I think) that you can't have both expiry based on a timeout and expiry when the browser is closed. So maybe the best bet is to keep the default and set your own timer in $_SESSION as others have suggested, thus rendering this answer pointless.

    0 讨论(0)
  • 2020-12-12 03:49

    Instead of setting it to one, why don't you set $_SESSION['logged_time'] = time(); and then check the time against time() in your application?

    If you'd like to actually expire the entire session, the exact specifics can change depending on your session handler, but for the default session handler (and any other well behaved session handler) you'll want to check out http://us3.php.net/manual/en/session.configuration.php

    0 讨论(0)
提交回复
热议问题