Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

session

login

Can anyone please suggest a best method in PHP to make a user logs-in from only one machine at a time.

like image 241
Joe Avatar asked Jun 01 '10 12:06

Joe


People also ask

Which of the following php functions is used to make a user logged out from a website?

php session_start(); /*This is the equivalent of login.

How do we check if a user is logged in in php?

session_start(); Check if $_SESSION["loggedIn" ] (is not) true - If not, redirect them to the login page.


2 Answers

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';
like image 103
Morfildur Avatar answered Sep 28 '22 20:09

Morfildur


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.

like image 27
Artelius Avatar answered Sep 28 '22 19:09

Artelius