PHP best practice keep track of logged in users

Constant Polling and using heartbeat are a good idea, but for some scenarios they may create useless load on server. I think you should think about the importance of keeping track of your users and use it very appropriately, especially considering the impacts your changes may have on load time.


Depending on how you want it to work you basically have two options:

  • Define a timeout after which you consider a user logged out
  • Use ajax/websockets/whatever to poll user

1: Timeout

This is the simpler use case. Every time the user requests a page, you update a timestamp in your database.

To find out how many users are online, you would do a query against this database and do a COUNT of users who have been active in the last N minutes.

This way you will get a relatively accurate idea of how many people are actively using the site at the moment.

2: Constant polling

This is a bit more complex to implement due to having to update the server with Ajax. Otherwise it works in a similar fashion to #1.

Whenever a user is on a page, you can keep a websocket open or do ajax requests every N seconds to the server.

This way you can get a pretty good idea of how many people have pages open on your site currently, but if a user leaves the page open in their browser and doesn't do anything, it would still count them as being online.

A slight modification to the idea would be to use a script on the client to monitor mouse movement. If the user doesn't move the mouse on your page for say 10 minutes, you would stop the polling or disconnect the websocket. This would fix the problem of showing users who are idle as being online.


To circumvent the problem with knowing if a user has logged out or browser crash ect, is to use a heartbeat/polling of sorts here is a stripped down example of how you can do that with jQuery

function heartbeat(){
   setTimeout(function(){
      $.ajax({ url: "http://example.com/api/heartbeat", cache: false,
      success: function(data){
        //Next beat
        heartbeat();
      }, dataType: "json"});
  }, 10000);//10secs
}

$(document).ready(function(){
    heartbeat();
});

http://example.com/api/heartbeat would keep the session alive & update a timestamp in your db, then on each page load you would check the time stamp with current time ect and if its lower then say 15 seconds then you would log them out.

Tags:

Php

Session