Auto Logout when user leaves the application without doing logout action

*爱你&永不变心* 提交于 2019-12-02 21:28:16

问题


Sometimes , an user leave an application without clicking on logout button, or do shutting down or hibernating of its Machine, pr even close all sessions (pages) which related to the application domain. So the server cannot knows that the user has been logged out!. If our case, we have a "time spent on last session" parameter to check the time of last session activated for each user.

We need to auto Logout user when he leaves the application without doing logout action! Any process to do?

Thank you in advance.


回答1:


You could set a cron job on the server to check for stale sessions But this is not a great solution since you have to deploy another solution (cron job) with your project. The way I would do it is have a check_credentials.php file included in your project that runs right after your DB connection, you will then add two fields in your users table for your projects users called: session_id AND last_checkin. The process will work like so:

Login:

  1. A session is created and a session_id can be retrieved from PHP on first hit (not logged in yet)
  2. If the user authenticates save the session_id to DB with current timestamp as last_checkin

Then you can have all the users do stale session checks at every page request:

Page Query:

  1. Delete session_id's from all users where last_checkin is older than 10min.
  2. Check if my current session_id = db.session_id
  3. If session don't match log out and send user to login.php
  4. if session_id's match then update last_checkin



回答2:


Try this:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 600)) {
    session_unset();
    session_destroy();
}
$_SESSION['LAST_ACTIVITY'] = time();

If $_SESSION['LAST_ACTIVITY'] > 600 no activity in last 600 seconds (10minutes) then destroy session.




回答3:


You can do something like ,

  1. Set a session once user has logged in to your Site.

    $_SESSION['last_activity_recorded'] = time();

    this will keep track the activity from user

  2. On every page update this session to updated time(ie current time)

  3. Check for inactivity from user (here 30 minutes) and take necessary steps in unsetting the login credentials(before updating the session on top of every page)

    if($_SESSION['last_activity_recorded'] < time()+30*60){ session_unset(); session_destroy(); }



来源:https://stackoverflow.com/questions/23010044/auto-logout-when-user-leaves-the-application-without-doing-logout-action

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!