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.
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.
actually the only accurate way to do that is using websocket, it will communicate with the user with real-time communication, try Ratchet.
You can achieve this by logging user's last-activity (on every page load, refresh, action one performs) in the database and then check session.gc_maxlifetime (in seconds) and calculate whether the user's session has expired or not, using user's last activity.
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.
You can run a function on each page request that updates a row in your database with your user's ID and a calculated timestamp for the future (e.g.
time()+(60*5);
- five minutes). Then whenever another user attempts to check if the first user is online, you can check it against the database using a 'pulse' check:If this query returns more than 0 rows, the user is considered online.
As per your scenario, you can use the below logic to check the status of the user:
Instead of checking whether the user is online or offline only depednding upon the value of the table column, use the session variable as well. for example consider below code:
You can enhance it further, but you get my point i hope.