如何设置会话超时?

时间:2015-01-05 07:46:01

标签: php session

有没有办法为会话设置时间限制?这意味着我的应用程序应在1小时后通过服务器设置注销,而不是像下面的编码级别那样。

<?php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 7200)) {
    // last request was more than 120 minutes ago
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
}

$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>

5 个答案:

答案 0 :(得分:3)

首先,存储用户上次发出请求的时间

<?php
 session_start();
 $_SESSION['LAST_ACTIVITY'] = time();
?>

在后续请求中,检查他们提前多久提出请求(本例中为30分钟)

<?php
  if (isset($_SESSION['LAST_ACTIVITY']){

  if ($_SESSION['LAST_ACTIVITY'] + 30 * 60 < time()) {

     // session timed out
     session_unset();     // unset $_SESSION variable for the run-time 
     session_destroy();   // destroy session data in storage
  } else {

    // session ok
 }
}
?>

答案 1 :(得分:3)

$timeout = 60*60;//1 hour session_start(); if (!isset($_SESSION['sessionTime'])) { $_SESSION['sessionTime'] = time() + $timeout;//first login, set timeout } else { if ($_SESSION['sessionTime'] < time()) {//over timeout, destroy session session_unset(); session_destroy(); } else { $_SESSION['sessionTime'] = time() + $timeout;//login in timeout, reset timeout } }

答案 2 :(得分:1)

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

/*
You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:
*/

if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session an invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}

//note that session.gc_maxlifetime should be at least equal to the life time of this custom expiration handler (1800 in this example).

description here

答案 3 :(得分:1)

导致问题是“不在编码级别” =&gt;您可以通过设置session.gc_maxlifetime和/或session.cookie_lifetime来通过php.ini和/或.htaccess实现此目的。

但编码级别是可靠的,并且可以容忍错误。

请参阅此Question的最佳答案以获取解释。

答案 4 :(得分:1)

详细说明请点击此链接:http://php.net/manual/en/function.session-set-cookie-params.php#96868

我们可以通过在php

中提供以下命令来通过会话参数提供
<?php
       // Here we start as usual
       session_set_cookie_params('3600'); // 1 hour
       session_start();
?>

希望有所帮助,谢谢你