how to get currently logged users in my website. I have a mysql table for maintain users.
I don't know how to display names who are logged in.
how to get currently logged users in my website. I have a mysql table for maintain users.
I don't know how to display names who are logged in.
Don't use a isOnline
field as others suggested. Instead use a lastSeen
field. You can put a timestamp in that field and update it either on every page view.
If you want to go easy on your system, you can update every couple of minutes (with a variable $lastUpdate
in the user session containing the timestamp of the last update of lastSeen
).
To find "online" users, you can select all the users that were lastSeen
in the last X minutes, for instance 10 minutes.
You can't know an exact number of online users, because you can't know if an user is looking at your page or he/she has already closed it. Anyway, a solution like this one is a good approximation.
Every hour or every day, depending on how many visitors you have, you can run a process to delete old entries.
There must be a field 'isOnline' in your users table, whose value will be either 0 or 1.
Whenever a user logs in, you update it to 1, and whenever user logs out, you'll update it to 0.
Currently online users can be retrieved by:
SELECT * FROM `users` WHERE `isOnline`='1'
My approach is to have table with user session tokens. Everytime user visits the site timestamp in session record is set to now. If session not touched for some amount of time it is expired and deleted from table (by cronjob or in some user requests as garbage collection). The same on logout. Structure is sessid, user_id, last_seen_ts
. You can just join this table with users to fetch their names.
Although, it can be done using only one table - store not only flag isOnline
, but some timestamp to expire users that just left your site not logging out.
You can create a column name isOnline and set it true when user get online. Then query it by isAvailable column
select * from users where isOnline = 'Y';
just create a field in your users table into your database with any name like status
that will suitable for you and update that filed with user login and logout with the value true
on login and false
on logout, and just check the true value that will provide you the all login users...
I think you need to have a flag for that in your database or create a file for every user in some temporary directory.