How to get the user online status (real time) in my website

Question!

I want to display which all user is online (real time; like any chatting module) on my site. I am using the below mention script to do this.

HTML:

<body onbeforeunload="Unload();" onmousedown="checkfunction();">

</body>

Javascript:

var doClose = false;

document.onkeydown = checkKeycode;

function checkKeycode(e){
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
 if(keycode == 17 ){
  doClose = true;
 }
}

function checkfunction(){ 
 doClose = true;
}

function Unload(){
 if(!doClose){
  set_user_log_out(<?php ehco $u_id ?>);
 }
}

The set_user_log_out function is to set the user logged out.

In the above mentioned java-script, i wanted to consider the below mentioned scenario.

  1. The user may open more than one tab in the browser. Or, he may open more than one browser (same browser only).
  2. The user may close one tab and visits the other tab.
  3. The user may clicks on one tab and simply closes the other tab.
  4. The user may close the browser without clicking on log-out option.
  5. The user may close the browser using keyboard short-cut (for eg. ctrl + F4).

So, i was checking the keycode (which key has been pressed using keyboard) as well. But, there is some issue with this code. Mentioned them below.

  • I have not found any solution to get the keycode of mulitple keys ( for eg. ctrl + F4)
  • Considering two tabs, if i type other url ( of the same site), the page keeps loading in firefox.
  • ctrl + r does not work fully.
  • Sometimes while trying to visit other page of the site, it simply executes the function 'set_user_log_out()' (happens in firefox only)

Please suggest me the needful for this. I have also gone through the below mentioned url.

How to Track the Online Status of Users of my WebSite?

But the function described on the above url does not consider my scenarios.

Thanks in advance.

By : Debashis


Answers
You should keep list of active sessions in database with last time of activity.

On each request to server you should update last activity time on specific session which made request. "Online users" are COUNT on this table with, lets say, last activity < 1 min ago

On log out function you should also remove specific session from this table



To make the idea Jerzy gave you "real time" you need to add some ajax. With ajax you can check the online users without leaving a page. Additionally you could add an away status to you database which means: Check if the user is still on the page but doesn't do any action etc. This is a quite simple approach :)

By : smoes


This video can help you solving your question :)
By: admin