Oli
Oli

Reputation: 16035

php destroy a session which is not the current session

If a user opens a session, I would like to destroy all other sessions that he might have.

I know session_destroy(); but it destroys only the current session.

How can I do to destroy another session? (I know the other session id)

Upvotes: 3

Views: 2936

Answers (3)

Kai Pommerenke
Kai Pommerenke

Reputation: 916

Set the default session handler before calling session_start():

session_set_save_handler(new \SessionHandler());

Then, destroy the session with the ID stored in $sessionID:

(new \SessionHandler())->destroy($sessionID);

Upvotes: 0

hakre
hakre

Reputation: 197684

As long as sessions contain a value that identifies the user it belongs to, this is technically possible.

For example, you can store sessions in a database, and then destroy all sessions but the current active one by deleting all other sessions from the database.

You wrote in your question you know already the other session id you want to destroy ($sessionIDDelte):

$backup = session_id($sessionIDDelte);
session_start(); # load session data
$_SESSION = array(); # do not use unset();
session_destroy(); # close and remove session

session_id($backup); # switch to current session
session_start();

This works independent to the session store. If you're using the file-system, you could just unlink the file with the session id you want to delete.

Upvotes: 3

Trott
Trott

Reputation: 70065

If you have the session id for the session you want to destroy, you can pass it to session_start() to resume that session, destroy it, then call session_start() again to create the new session. I haven't tried this to confirm it will work, but it seems like it ought to.

If you do not have the session id for the session you want to destroy, I'm not sure there's a sane, clean, portable way to do this.

Upvotes: 6

Related Questions