PHP中的会话超时:最佳做法 [英] Session timeouts in PHP: best practices
问题描述
session.gc_maxlifetime
与 session_cache_expire()
之间的实际差异是什么?
What is the actual difference between session.gc_maxlifetime
and session_cache_expire()
?
假设我希望用户会话在非活动15分钟后无效(在第一次打开后不是15分钟)。
Suppose I want the users session to be invalid after 15 minutes of non-activity (and not 15 after it was first opened). Which one of these will help me there?
我也知道我可以做 session_set_cookie_params()
用户的cookie在一定的时间内过期。但是,Cookie到期和实际会话在服务器端到期是不一样的;
I also know I can do session_set_cookie_params()
which can set the user's cookie to expire in some amount of time. However, the cookie expiring and the actual session expiring on the server side are not the same; does this also delete the session when the cookie has expired?
另一个解决方案是简单
$ _ SESSION ['last_time '] = time()
,并将会话与当前时间进行比较,基于此删除会话。我希望有一个更多的内置机制处理这个。
Another solution I have though of is simple
$_SESSION['last_time'] = time()
on every request, and comparing the session to the current time, deleting the session based on that. I was hoping there was a more "built-in" mechanism for handling this though.
谢谢。
推荐答案
每次 session_start 被称为会话文件时间戳(如果存在)更新,用于计算是否已超过session.gc_maxlifetime。
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.
更重要的是,您不能依赖于会话在session.gc_maxlifetime时间后过期超过。
More importantly you can't depend on a session to expire after session.gc_maxlifetime time has been exceeded.
PHP在加载当前会话后使用 session.gc_probability 和 session.gc_divisor 它计算垃圾收集将运行的概率。
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.
此示例替换 session_start 并强制超时:
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;
}
这篇关于PHP中的会话超时:最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!