开发者

Number of users logged in/out with session expire?

I'm running a php login script on my开发者_StackOverflow社区 server. Whenever a user logs in the username is stored in $_SESSION['username'] and there exists a field in one of my DB tables called nonline used to store the number of users logged in.

When a user logs in, the value of nonline increases by one. And whenever a user logs out it decreases by one. Pretty neat so far. :P

The problem starts when, most of the users, like me, do not click logout, or visit the logout page as such. They log in, and just close their browser/tab when done. Doing so doesn't decrease the nonline value. So the value remains as such, even when the user is no more browsing my website.

Is there any way I can determine the number of users actually looking at my website at any given time so that its value changes even when a user closes his browser instead of clicking logout? I'm not using cookies for login.


Normally this will be done with a table which tracks last action, or last page load. The number n_online (you may want to add the _, noline starts with no, which is a little odd at first glance) will be the number who have made some form of action in the last n seconds - the number of people who actively logged out.


Unfortunately, there is not. Any solution that does what you want would involve the browser firing an HTTP request of some kind when the tab/window is closed, and this isn't going to happen.

The best you can do is have the users' sessions time out after a relatively short time (e.g. 15 minutes) and perform aggressive cleanup of expired sessions on every script that wants to know the actual number of active users. Be aware that this will be bad for performance.

If 15 minutes is still too long for you and you cannot decrease the session lifetime (because it would annoy your users if they were logged out after 10 seconds of inactivity), you can have your pages "ping" the server using AJAX to keep the session alive. This will allow you to have almost real-time results, but it will probably kill your performance, it will not work for users with JavaScript disabled, and is prone to malfunction if a user experiences transient connectivity problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜