如何设置会话超时?

How to set timeout for 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
?>
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

首先,存储用户最后一次请求的时间

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

因为问题是 "not on coding level" => 你可以通过 php.ini and/or .htaccess 通过设置 session.gc_maxlifetime 来实现and/or session.cookie_lifetime。

但是编码级别更可靠,容错性更好。

查看此 Question 的最佳答案以获取解释。

如需详细说明,请阅读此 link: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();
?>

希望对你有帮助谢谢

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