Best method in PHP for a user to log in from one machine at a time

Can someone suggest a better method in PHP so that a user can log in from only one computer at a time.

+4
source share
2 answers

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

Table user

  • user_id
  • Username
  • password
  • token

Login:

  • create custom token
  • User UPDATE SET token = 'MyRandomToken' WHERE username = 'username' and password = 'password';
  • $ _ SESSION ['login_token'] = 'MyRandomToken';

On each page:

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

This ensures that the login expires automatically if there is a new login. At any time, there can be only one registered user per account.

UPDATE

Just saw your comment on the Question. My answer does not work for you, as it does not prohibit the second entry, but instead cancels the previous entry.

If you want to prevent a second login, then the best solution is to use the timestamp that you update on each page:

When logging in:

(Assuming MySQL :)

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

If the string is found, then the account exists, and the login is not blocked by another login. You might want to split this into two requests (first check the login, and then check the last access) to give the best error message for failed logins, otherwise it is either "account does not exist" or "locked".

On each page:

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

You cannot do this solely using session variables, since logins from two separate machines will have separate sessions.

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

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

However, you will need to prevent the re-inclusion of the old session, either by using the timeout in the session variables, or add another column to the database, for example login_session_id , and disconnect the user if the session identifier does not match that in the database.

+4
source

Source: https://habr.com/ru/post/1311514/


All Articles