PHP计数登录用户 [英] PHP Count Logged-In Users

查看:79
本文介绍了PHP计数登录用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚如何计算应用程序中已登录用户的数量时遇到麻烦.

I'm having trouble figuring out how I can count the number of logged-in users in my application.

我拥有的内容:当用户登录时,他们获得一个会话(该会话在用户要访问受保护的页面时使用),并且用户表中该用户的IsLoggedIn列为设置为1表示用户已登录.当用户注销时,该值重新设置为0.对users表中的1进行计数可以很容易地返回已登录的用户数.但是...

What I have: When a user logs in, they get a session (which is used when the user wants to visit a protected page) and the IsLoggedIn column for the user in the users table is set to 1 to indicate that the user is logged in. When the user logs out, the value is set back to 0. Counting the number of 1s in the users table makes it easy to return the number of users logged-in. But...

问题:如果用户关闭浏览器但未注销,则数据库中的值保持为1,表示即使关闭会话的浏览器会话已结束,用户仍然可以登录

The Problem: If the user closes the browser without logging out, the value in the database stays 1, indicating that the user is still logged in even though their session has ended when they closed the browser.

问题:有人可以建议这样做的正确方法吗?

Question: Could some one suggest a proper way of doing this?

推荐答案

您应该添加LastTimeSeen列,而不是IsLoggedIn列.每当有人访问页面时,您都会更新该列:

Rather than a IsLoggedIn column, you should add a LastTimeSeen column. Any time a person visits a page you update the column:

UPDATE members SET LastTimeSeen = NOW() WHERE id = $the_user_id

然后,您可以在任意时刻使用该查询来获取网站上的人数:

Then to get how many people are on the site at any given moment you use the query:

SELECT COUNT(*) FROM members WHERE LastTimeSeen > DATE_SUB(NOW(), INTERVAL 5 MINUTE)

这显示了过去5分钟内有多少人浏览过某个页面,这是您没有更复杂的解决方案所能获得的最好的结果.

That shows how many people have viewed a page in the past 5 minutes, which is the best you're gonna get without a much more complicated solution.

这篇关于PHP计数登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆