views:

688

answers:

3

Hi guys I have a simple membership based website where users log in and have their own profiles. I woudl like to be able to tell at any given point in time how many users or rather which users are currently logged into my website.

Its a simple membership based system in php. One way I uderstand it creating a table in a db and storing login details there and session data as well but can this be done in some other way i.e. anyway to find out how many sessions have been started and all the unique users online.

+5  A: 

The best way to do this is record the lastActivityTime for each user. When they access a page, log the time in their db-record. Once you're doing that, run a simple query to count all records that have a lastActivityTime less than 5 minutes from the Current Time.

So rather than asking "how many users are logged in," you're asking "how many users were recently active."

Jonathan Sampson
A: 

One method I've used is to write a custom session handler - there are plenty of examples on php.net. Once the session data is in SQL there's a lot more you can do with it.

nOw2
+1  A: 

The key problem with the whole 'monitoring active sessions' issue is that you (the server) are not necessarily in full control of the session. User's browsers can expire the sessions at any given time, so you cannot guarantee active users at any point.

If it is extremely important to know the current users, then add a column to their user table specifying a timestamp, and update that field every time they load a page. If that column is less than about a minute out of date, then they can be considered active.

An extra thing you can do (used a lot by online chatrooms to maintain an active 'chat' list), is to poll a page at a given interval (using AJAX), and then even if they don't refresh the page you still know they are there. If an ajax request doesn't arrive at the specified interval, the user has navigated away, or shut their browser.

Kazar