How do I find out total number of sessions created i.e. number of logged in users?

感情迁移 提交于 2019-12-11 12:36:25

问题


Hi guys I have a simple membership based website where users log in and have their own profiles. I woudl like to be able to tell at any given point in time how many users or rather which users are currently logged into my website.

Its a simple membership based system in php. One way I uderstand it creating a table in a db and storing login details there and session data as well but can this be done in some other way i.e. anyway to find out how many sessions have been started and all the unique users online.


回答1:


The best way to do this is record the lastActivityTime for each user. When they access a page, log the time in their db-record. Once you're doing that, run a simple query to count all records that have a lastActivityTime less than 5 minutes from the Current Time.

So rather than asking "how many users are logged in," you're asking "how many users were recently active."




回答2:


The key problem with the whole 'monitoring active sessions' issue is that you (the server) are not necessarily in full control of the session. User's browsers can expire the sessions at any given time, so you cannot guarantee active users at any point.

If it is extremely important to know the current users, then add a column to their user table specifying a timestamp, and update that field every time they load a page. If that column is less than about a minute out of date, then they can be considered active.

An extra thing you can do (used a lot by online chatrooms to maintain an active 'chat' list), is to poll a page at a given interval (using AJAX), and then even if they don't refresh the page you still know they are there. If an ajax request doesn't arrive at the specified interval, the user has navigated away, or shut their browser.




回答3:


One method I've used is to write a custom session handler - there are plenty of examples on php.net. Once the session data is in SQL there's a lot more you can do with it.



来源:https://stackoverflow.com/questions/978333/how-do-i-find-out-total-number-of-sessions-created-i-e-number-of-logged-in-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!