Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle user online status when he/she close the browser?

Tags:

php

I am having table to track user online status by setting 'is_online' field to 1. Now User get logged in the site and shut down his/her system or power down at that time he/she logged in. Here in database 'is_login' has the value '1' which means he is still using the site.

So I have to do some logic to change that value to '0'.

How can i handle this situation using PHP ?

like image 739
mymotherland Avatar asked Jun 17 '11 12:06

mymotherland


2 Answers

The normal solution is to store a timestamp in the table which you update every time the user does something. Users with a recent timestamp (say, five minutes) are shown as logged in, everybody else are logged out.

It doesn't even have to be updated on every page load. Keep a timestamp in the session with the last update time as well, and only update the table when the database flag are about to expire.

like image 151
Emil Vikström Avatar answered Nov 15 '22 11:11

Emil Vikström


Store an time-since-last-activity. When it's been longer then a specified time - treat as if offline. You should replace the is_online with an DateTime field, and update it every time the logged in user visits the website.

On the place you want to select all online users, instead of :

SELECT * FROM users WHERE is_online = 1

You could use:

SELECT * FROM users WHERE is_online >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
like image 20
Wesley van Opdorp Avatar answered Nov 15 '22 12:11

Wesley van Opdorp