Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a users has already logged in?

Tags:

php

session

how do you check if a user already has logged in?

so that if a user in another browser cant log in with the same account.

also, is this a good solution or should i let the user log in in the other browser and then log out the current user and display a message (you are logged in from another location) just like messenger does?

like image 937
ajsie Avatar asked Dec 27 '09 02:12

ajsie


2 Answers

Using sessions is a good way to do this, and is a very common method for controlling authentication.

The flow usually looks something like this:

  • User visits site, and session_start() is called. A unique session identifier is set for that visitor (ie. a cookie).
  • User submits his login credentials to a login form
  • Login credentials are verified, and this fact is stored in the session data with $_SESSION['logged_in'] = true, or something similar
  • For the rest of the user's time on the site, you can check $_SESSION['logged_in'] to see if the user has logged in.

In order to control a user's logins, you could simply have a field in a database (users table is fine) indicating what the current session id is (retrieved with session_id()) for the user, and if it doesn't match the cookie value you just received, then you immediately call session_destroy() for that id, and consider the user as logged out.

Using $_SESSION means you don't have to worry about generating your own tokens, and gives you the power of the built-in superglobals to facilitate storing information about the user's authentication status.

Personally, I would allow multiple sessions to be active for a user for most web sites, as there's usually not a good reason not to, but it obviously depends on the nature of the site. However, storing the current active session id as mentioned above is a pretty simple way to accomplish this.

like image 167
zombat Avatar answered Oct 06 '22 02:10

zombat


Generate a random token upon signing in (or use the sessionid), and store this in the database and in the users cookie. With each page access, ensure that the users token matches the database entry. If the two don't match, alert the user that they've logged in elsewhere.

You could also store the login time, which subsequently would be the time the token was assigned, and require 30 minutes before permitting another user to login with the same ID.

like image 36
Sampson Avatar answered Oct 06 '22 02:10

Sampson