当PHP中没有活动时,会话将终止 [英] expire session when there is no activity in PHP
问题描述
我在Internet上找到了许多教程,当您在某个限制后(例如30分钟左右)使会话期满时,但是我想在没有活动的情况下使会话期满,
引用了著名的SO问题< a href = https://stackoverflow.com/a/1270960/1091386>解决方案很简单:
I found many tutorials on Internet when you expire a session after a certain limit, like after 30 minutes or so, But I want to expire a session when there is no activity, quoting from a famous SO question the solution is straight forward:
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
,但是我是否必须更新 $ _SESSION ['LAST_ACTIVITY']
是否在每个请求上?
but do I have to update the $_SESSION['LAST_ACTIVITY']
on each request?
预先假定的答案是,但是我有一个包含200多个php页面的大型站点,更新 $ _ SESSION ['LAST_ACTIVITY ']
。
The pre-assumed answer is Yes, but I have a big site containing 200+ php pages and it's hectic to update $_SESSION['LAST_ACTIVITY']
on each request.
还有其他方法吗?在所有文件中,唯一的共同点是一个用于数据库连接的配置文件。
Is there any other way of doing this? The only common thing among all files is one config file for DB connection.
推荐答案
您还可以更新 $ _ SESSION ['LAST_ACTIVITY']
每分钟仅一次(例如),但是会话将不会在恰好30分钟后销毁。
You could also update the $_SESSION['LAST_ACTIVITY']
only (eg) once per minute but than the session will not be destroyed after exactly 30 minutes.
if (isset($_SESSION["LAST_ACTIVITY"])) {
if (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
} else if (time() - $_SESSION["LAST_ACTIVITY"] > 60) {
$_SESSION["LAST_ACTIVITY"] = time(); // update last activity time stamp
}
}
最简单的方法为此,将代码放入配置文件中,因为我不希望您更改所有200个php文件。
And the easiest way to do this is put the code in the config file since I don't think you want to change all 200 php files.
这篇关于当PHP中没有活动时,会话将终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!