views:

47

answers:

2

I currently use PHP sessions as the basis of my user login system, with a successful login setting $_SESSION['userid']. This allows a user to log in to the same account from multiple machines.

However, I'd like to implement the following features:

  1. Log out everywhere, similar to what Stack Overflow has.
  2. See where else one is logged in.

Both will likely require more than just a session variable, and I'm willing to put more information into the database to accomplish these. What is a standard way to do the above?

A: 

If you want to destroy session and logout, you can use session_destroy() function. To delete specific session variable you can do this way:

unset($_SESSION['userid']);
session_destroy();
Sarfraz
+2  A: 

Create a new database table to store sessions, and then instead of storing information directly in $_SESSION, just store an ID referring to a row in your new session table. This table can contain information like IP address, username, and the time of last activity.

Your application should check the sessions table against what it has in $_SESSION, so when you remove all rows in the table for a particular user, every session will be invalidated, wherever it is. You can also query for all rows belonging to a particular user, so you can show where they have active sessions.

You'll have to start thinking about handling where a user leaves their session without explicitly logging out - possibly a scheduled job that runs every hour or day, clearing out session rows that haven't had any activity in a certain period of time.

Nick
If you want, you can use `session_set_save_handler()` and make your entire session data on a database.
Chacha102
Nice one - didn't know about that function.
Nick