Check Whose Online Using Database – PHP

While going through a project where theres a need of taking some action on those users who are currently logged in on to the website, I went through the following solution. Please note that, you will be needing a scripting language, database and ajax.

Here is what I think you should do, to get the solution to this problem.

Create a table, for example user_session in database, having the fields:
– user_id (integer & unique)
– last_seen (date time)

Now you can simply call ajax within your whole website, for example in your main index file, header or footer, like after every 1 minute or few seconds, as per your need, which will be INSERTING or UPDATING the user_id with the date and time of Ajax call, to be updated in last_seen field.

On the other hand, you have to run a script or a cronjob, which will be running in like after every few seconds or minutes, DELETING the records which are say 5 minutes older. The DELETE query should look like:

DELETE FROM user_session
WHERE last_seen < DATE_SUB(NOW(), INTERVAL 5 MINUTE); Through these steps, u will only be having those users in your user_session table who are currently online, so you can perform any action with those users, or display the count of online users to your website etc. If you have any other great solution to the problem, or have any other comments or suggestions, feel free to comment on the post.

Uncategorised

Leave a Reply

Your email address will not be published. Required fields are marked *