How to learn online user number in PHP? [closed]

2019-09-22 11:45发布

问题:

I'm developing a forum and I need to count the number of online persons.

According to old questions which are related to it, they says the count() function should be used.

But the count() function counts just specific user's session variables. I mean in codeigniter, count($_SESSION['user']) gives number 2 and this number points to $_SESSION['user']['name'] and $_SESSION['user']['group'].

So every user sees number 2 in their screen as online person number. But I need to number of allocated $_SESSION['user'] variable in the server, not number of specific session variable's sub variables. What is the solution? How can I detect number of online persons?

回答1:

In this case, you want to have a database, preferably MySQL and update the users table with CURRENT_TIMESTAMP() whenever the user reloads the page or does anything on the site.

Afterwards, if you want to obtain current users online, you can do

SELECT COUNT(*) FROM users WHERE last_activity > NOW() - INTERVAL 5 MINUTE;