简体   繁体   English

在一定时间后注销用户

[英]Logout a user after certain time

I'm currently storing a timestamp of the users last activity in my database in which if that hasn't been updated for 15 minutes (for testing doing 2 minutes) I want it to log the user out.我目前正在我的数据库中存储用户上次活动的时间戳,如果在 15 分钟内没有更新(用于测试 2 分钟),我希望它注销用户。

I have been trying different things but they all seem to log me out even though they shouldn't be.我一直在尝试不同的事情,但他们似乎都让我退出,即使他们不应该这样做。

Example of something I've tried我试过的东西的例子

    $Online = time() - 120;
    if ($CheckOnline['lastaction'] < $Online){
    header("Location: Logout.php");
    session_destroy();
}

Am I going at this the wrong way.?我是不是走错路了。? If I do $Online < $CheckOnline['lastaction'] it keeps me logged in but never logs me out.如果我这样做 $Online < $CheckOnline['lastaction'] 它会让我保持登录状态,但永远不会让我退出。

Thank you in advance!先感谢您!

Supposing the 'lastaction' is in epoch time format, this would be quite easy.假设“lastaction”是纪元时间格式,这将非常容易。 You can check by the current time minus the last action time, that will give you the time in-between the actions.您可以通过当前时间减去上次操作时间来检查,这将为您提供操作之间的时间。 You can do something like this:你可以这样做:

$maxTimeAllowed = 120; // 2 Mins
if ((time() - $CheckOnline['lastaction']) > $maxTimeAllowed){
    session_start();
    session_destroy();
    header("Location: Logout.php");
}

I should also mention, in order for you to destory a session you must start it first, but I figure you would handle that logic either in your logout.php or on the page this will be run on, but i've included it just incase.我还应该提到,为了让您破坏 session,您必须先启动它,但我认为您可以在 logout.php 或将运行的页面上处理该逻辑,但我只是将其包含在内如果。

Another alternative is via javascript.另一种选择是通过 javascript。

setTimeout(() => {
   window.location = 'logout.php'
}, 120000) // 120000 because JS counts in milliseconds

That way, this will ensure that no matter what the user will be logged out in 2m, not just when they make another request.这样,这将确保无论用户在 2m 内注销什么,而不仅仅是在他们发出另一个请求时。

Sidenote: If the date/time in your database is stored not as epoch time, it might be worth using strtotime() to convert them, as epoch time is much easier to work with.旁注:如果数据库中的日期/时间不是以纪元时间存储的,则可能值得使用 strtotime() 来转换它们,因为纪元时间更容易使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM