问题
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
but do I have to update the $_SESSION['LAST_ACTIVITY']
on each request?
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.
回答1:
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
}
}
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.
来源:https://stackoverflow.com/questions/19215300/expire-session-when-there-is-no-activity-in-php