简体   繁体   中英

Best method in PHP to make a user logs in from one machine at a time

任何人都可以在PHP中建议一个最好的方法,让用户一次只能从一台机器登录。

You can't do this purely using session variables because logins from two separate machines will have separate sessions.

One solution is to have a database TIMESTAMP column called last_active_time . Set last_active_time to NULL when the user logs out.

If last_active_time is more than X minutes ago (where X is the timeout time), assume the user's session has timed out and allow the connection from the new location.

However, you will need to prevent the old session from becoming active again, either by implementing a timeout in the session variables, or add another column like login_session_id to the DB, and kick the user off if the session ID does not match the one in the DB.

Set a key in your session that you store in the database in the user table:

Table User

  • user_id
  • username
  • password
  • token

On Login:

  • create random token
  • UPDATE user SET token='MyRandomToken' WHERE username='username' and password='password';
  • $_SESSION['login_token'] = 'MyRandomToken';

On every page:

  • SELECT user_id, username, token FROM user WHERE token='$_SESSION['login_token']';
  • If not found then the logiin token is no longer valid.

This makes sure that a login expires automatically if there is a newer login. There can be only one logged in user per account at any time.

UPDATE

Just saw your comment to the Question. My answer does not work for you as it doesn't disallow a second login but instead invalidates any previous login.

If you want to prevent a second login then using a timestamp that you update on every page is the best solution:

On login:

(Assuming MySQL:)

SELECT user_id
FROM user
WHERE username='username'
AND password='password'
AND last_access < DATE_SUB(NOW(), INTERVAL 10 MINUTE);

If a row was found then the account exists and the login is not blocked by another login. You might want to split that into two queries (first check login, then check last access) to give a better error message for failed logins, otherwise it's either "account does not exist" or "blocked".

On every page:

UPDATE user
SET last_access=NOW()
WHERE user_id='CurrentUserId';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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