Web Owl
Web Owl

Reputation: 569

Show all users currently signed in?

I am assuming I cannot do this using sessions but rather the DATABASE. So the user would sign in, it would set their TIMESTAMP and I display that from the database. Then it becomes deleted when the user logs out or their session is terminated. How would the code look for this?

The better question is, is my logic correct? Would this work? Does this make sense?

Upvotes: 0

Views: 190

Answers (2)

abraj
abraj

Reputation: 349

By default application servers store session data in temporary files on the server.

By storing session data in a database table you are able to create an interface that will show information about the users that are logged in. Apart from that, using this (database) approach is a serious advantage if you need to scale your application by adding more than one server.

One of the most popular ways to implement such a functionality is to create a session table containing your users' session data. This may look like:

create table session (
   id number primary key, 
   data varchar(240), 
   timestamp date
);

The data column stores all the session data in a serialized form this is deserialized each time a user requests the data.

Serialization and deserialization may have inbuilt support depending on the platform you are using. For example, if you are using PHP, the functions session_encode and session_decode may be found useful.

Upvotes: 2

filype
filype

Reputation: 8380

You can't find out when a user logs out in PHP and the Javascript workarounds are a bit far from a stable solution.

A couple of things you need to do: Create a column in your user table called last_activity and update their last_activity to the current time whenever a user loads a page.

For a list of who's online, query the db for users with last_activity values more recent than 10 or 20 or whatever minutes ago.

To update the last_activity column use:

UPDATE users SET last_activity=CURRENT_TIMESTAMP() WHERE id=2

For a list of users online

SELECT * FROM users where last_activity >= (CURRENT_TIMESTAMP()-(60*20))

Upvotes: 1

Related Questions