I need to show my users other users who are currently online i could have maintained a log of login and logout and based on that i could count total people online but many a time users don't log out and so my count would not be valid .
Here are criteria to show that user is online in:
user has just logged in
user is currently viewing the page
user has the left tab open but currently browsing in another tab
use has tab open but has minimized the web browser
Here are criteria when use should not be shown online
user has logged out;
user dosent wants to be shown online
user closed the browser with tab was open
user closed the browser
I dont know how to go ahead with this. I am using php on server side and mysql and mongo db as databases please help me with this ...
Thanks in advance
There's just a method to be somehow sure that a user is "online". To accomplish it you need to understand that with "online" people usually refer to an user being online in that moment; while checking this is not easy (or even not possible), to check if a user has made any action within an x
amount of time is very easy, and it's the choice most of the programmers do.
It's pretty easy:
last_activity
.last_activity
to the current time()
stamp.$x
amount of seconds that a user can be idle (not browsing any new page) before being considered offline. (Usually it is 15 min or 30 min or 1 hour)."SELECT * FROM users WHERE last_activity >= ". (time() - $x)
$x
seconds.Unlike other things, in PHP and with web browser there's no way to detect for sure when a user has closed one of your page in the browser, so it's technically impossible to know whenever a user has closed the browser window or exit your website.
By the way, I lied, there's a method but it's really expensive so please think a lot about it because it could crash your server or something like that:
last_activity
field in the user table (as below).y
seconds require update.php
(just an example).y
to be the bigger number you can (< 30 seconds may be bad)).update.php
where you update last_activity
with the current time()
stamp.$x = $y + 1
when you want to find out the online people.With the latest solution you can be sure that whenever a user is not on the page anymore, he is also not running the AJAX call and then within y
seconds it will be not considered online anymore. It's a very similar solution to the first one, but you can set y
to be smaller than the previous x
. In this way you have more informations about the current state of the browser window of the user but you have much more database load than before.
Almost all sites that show users online actually show "users online within the last X minutes". Just keep track of the last time each user loaded a page, and count how many users did that in the last X minutes (X being whatever you want to consider "online")