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?
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:
$_SESSION['logged_in'] = true
, or something similar$_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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With