Search code examples
phpforumyii2

Forum Current Online users


I have my own forum script in PHP (Yii2 Actually) and I want to show online users. It would be easy if users would be active up until they log out. But that is not the case. Most of the time user leave their machines logged in but they are not active. Here I could use time limit (renewing time with each request and deleting those which are past that time limit) but isn't that overkill?

Is there any popular/better way of monitoring online users in the forum?


Solution

  • One possible way is to intercept user interface events in javascript and send an ajax notification to the server that the user is still there. Of course, this should be buffered, so that you don't get flooded with requests when the user moves the mouse. Something along the lines of

    $('body').on('keydown mousemove scroll', function() {
    
         clearTimeout(notifyTimer);
         notifyTimer = setTimeout(function() {
               $.get('my-server.com/user-is-active');
         }, 60 * 1000);
    });
    

    On the server side, update the last-active field in the users table with the current timestamp. When displaying online users, select those with last-active > now - 15 min.