PHP: Most Efficient Way to Track if a User is Online? PHP: Most Efficient Way to Track if a User is Online? php php

PHP: Most Efficient Way to Track if a User is Online?


Generally speaking it's a common practice to add a column to the users table to store the lastActivity time. Anytime the user logs in, or accesses a page, store the current time in that field. If you want to know whether or not they are online, see if the last recorded time is within a certain window - say, five minutes. You can query all rows to see how many users are currently online as a result.

I wouldn't be too worried about running queries every few seconds - your server can handle it (assuming these are well-written and not very verbose).


you can use datetime for field type and don't forget to record user IP so you can track time o


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

Define a timeout after which you consider a user logged outUse 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.