Track or Count Online Users List

During interview, this is the common question which are asked by the interviewer that How can we track or count total number of online users. This is tricky but really simple question and most of the times interviewee is not able to response on this simple question.

There are two solutions by which you can get the number of online users.

SOLUTION I:

Whenever user come on your site and logged-in on the site. Then set a flag value in DB. And reset the flag whenever user logged-out the site. But this is a major issue in this case. You are totally dependent on the user’s logged-out step. But if user left the site and close the browser or directly goes to other site you can’t reset the flag in the DB. DB state will show that the user is online while he/she is not online. So, this is not recommended.

SOLUTION II:

Make another table for this purpose and add at least 4 fields in this table which are

  1. username
  2. datetime
  3. ipAddress
  4. session value

Whenever user logged-in on the site insert a record in this table. Also store the session values in COOKIE. Now, on each page first try to read the COOKIE contains the value of session. If the session value found then update the table row with the current datetime where the session value exist.

Now, at this point you can get the information that how many people are currently logged In. Also by the username you can also get the user’s information. But you need to fix you timings that for how long the user’s session should alive. It means if you think that if there is no activity on the site by user within last 10 minutes then it suppose that user has left the site. So, you must get only count of people in last 10 minutes.

You can implement this in any server site scripting like PHP, ASP .Net, CGI, Perl, Ruby etc.