PHP 会话超时,代码问题
我有一些代码可以在 x 秒不活动后将用户注销。问题是它会在指定的时间之前将它们注销,甚至不计算不活动情况。
这是代码:
<?php
$_SESSION['loginTime'] = time();
if($_SESSION['loginTime'] < time()+10*60){
$error_msg ="Logged out due to inactivity";
showLoginPasswordProtect($error_msg);
session_destroy();
}
?
I have some code that will log the user out after x seconds of inactivity. The problem is that it logs them out before the time specified it doesn't even count the inactivity.
This is the code:
<?php
$_SESSION['loginTime'] = time();
if($_SESSION['loginTime'] < time()+10*60){
$error_msg ="Logged out due to inactivity";
showLoginPasswordProtect($error_msg);
session_destroy();
}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么
$_SESSION['loginTime']
是他们登录的时间戳(希望如此),它总是小于当前时间戳,因为您每秒添加一个。所以你需要这样做:这样,如果 600 秒过去了,它将运行该语句。
Well
$_SESSION['loginTime']
is the timestamp that they logged in (hopefully) which will always be less than the current timestamp, because you add one for every second. So you need to do this:This way it will run the statement if 600 seconds have passed.
看看您的脚本正在做什么:
$_SESSION['loginTime'] = time();
...将 'loginTime' 设置为当前时间。假设当前时间是 '10'
if($_SESSION['loginTime'] < time()+10*60)
...因为我们假设当前时间是 10,那么
time()+10*60
变为10+10*60 = 610
,if() 变为:if (10 < 610) {
code>因此,您的代码将始终注销用户,因为您的逻辑已损坏。
您需要在登录脚本中设置
loginTime
一次,而不是像现在一样每次都设置。Look at what your script is doing:
$_SESSION['loginTime'] = time();
... sets the 'loginTime' to the current time. Let's say the current time is '10'
if($_SESSION['loginTime'] < time()+10*60)
... since we're assuming the current time is 10, then
time()+10*60
becomes10+10*60 = 610
, and the if() becomes:if (10 < 610) {
So, your code will ALWAYS log out the user, since your logic is broken.
You need to set the
loginTime
ONCE, in the login script, instead of setting it each time, as you are now.您需要在单独的脚本中设置
$_SESSION['loginTime']
,大概是在用户通过身份验证之后。然后在这个脚本中你需要计算出会话时间和当前时间之间的差异,然后看看它是否大于你的超时阈值。
例如:
You need to set
$_SESSION['loginTime']
in a separate script, presumably after the user is authenticated.Then in this script you need to figure out the difference between the session time and the current time, and then see if it is larger than your timeout threshold.
For example: