Moseleyi
Moseleyi

Reputation: 2859

PHP - closing sessions

I have read this topic as I was wondering if it's possible to close a session remotely. It is possible I might not be understanding the topic entirely so please let me know.

Ideally if somebody is logged in to my application and then logs again using different PC - I would like to close the other session without using the database.

I've used this:

session_start();
session_id($ns);
session_destroy();
ob_start(); 
session_start();
session_regenerate_id();

but it doesn't actually destroy the session. Am I doing something incorrectly?

-- edit

Forgot to add few details. I only want to contact the database once - when person logs in again - the current session_id is then added to $ns variable.

But I don't want to access the DB on each page. Before I log somebody in I am reading the session from DB and trying to destroy it and start a new one.

Changed order of session_start() and session_id($ns) and still can't do it

Upvotes: 1

Views: 107

Answers (2)

Max
Max

Reputation: 2643

Store the $_server['remotehost'] in the user table of the database as the user logs on.

Then compare it to the current host every time the user accesses your application.

If they don't match destroy the current session and ask the user to login again.

Upvotes: 1

jbafford
jbafford

Reputation: 5668

When specifying a session id, session_id() must be called before session_start().

If you want to log a user out of other logged in sessions when they log in, you're going to have to do further work, most likely involving the database. Otherwise, you have no way of knowing which session to destroy.

It's generally not necessary to actually destroy the session until it's accessed again, so going through the trouble of getting a session id just so you can destroy it is more work than necessary. But if you really want to do it that way, then you should store the user's session id in the database, and use it to destroy their prior session.

A better approach would be to store a token of some sort (unique string, login time, or something) in both the session and the database that, on each page access, can then be validated. If the token in the database does not match the token in the session, the session is old/invalid and the user can be logged out at that time.

Upvotes: 2

Related Questions