Debashis
Debashis

Reputation: 596

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

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.

Please suggest what I need 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.

Upvotes: 1

Views: 7216

Answers (3)

user5296504
user5296504

Reputation:

I had a php script which stores all the online users in a json file.. then I use jquery to store every user in a li-table:

function getAllUsers(){
  $.getJSON('online.php',function(data){
   $.each(data, function(i, data){
        if(data.user_status == 'online') {
          $("#online-user")
          .append("<tr><td>" + data.user_id + "</td><td>"
                  + data.user_name + "</td><td>"
                  + data.user_status + "</td></tr>)");
         }
   });
   })
}

Upvotes: 0

smoes
smoes

Reputation: 601

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 :)

Upvotes: 0

Jerzy Zawadzki
Jerzy Zawadzki

Reputation: 1985

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

Upvotes: 2

Related Questions