Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if a user is online in a website with php and mysql driven databases?

I'm building a community website. Users will login and logout as usually.

I use the attribute status online/offline to set the user's status. But what if a user just clicks the X button or disconnects otherwise without logging out?

Lately my computer crashed, when I opened the site with my laptop I could not login because I don't allow login in two places. I go to PHPMyAdmin and I see my status still online. Is there any fix for this.

I tried the last_time activitiy thing but that doesn't work in case of a computer crash! And there was nothing neither interactivity or refresh to update the table.

like image 526
aygeta Avatar asked Nov 06 '11 09:11

aygeta


2 Answers

Because of the nature of the web, you can't know when a user disconnects, yanks the cable or shuts down his computer without politely telling you.

You could have a script (AJAX) check every X minutes to see if the browser still responds, and if not, toggle offline - but that would consume extra resources. This is how for example an IRCd works: they PING you, you PONG back. If you don't pong back, you timeout and get disconnected from the server.

HTTP is stateless, there is no other built-in solution. Maybe HTML5 and sockets, but that would be the same principle as just plain AJAX.

like image 20
Konerak Avatar answered Sep 28 '22 11:09

Konerak


You don't need the online/offline flag, you just need to save the last activitity time. When displaying the user status, if last activity time is less than now+15 minutes then user is online, offline otherwise.

like image 116
Volodymyr Smotesko Avatar answered Sep 28 '22 12:09

Volodymyr Smotesko