How to use PHP to count the number of online users?

To track the number of online users, you can utilize PHP and a database. One simple method for achieving this is as follows:

  1. Create a database table to store information of online users, which includes user ID and last access time.
  2. Add PHP code at the top and bottom of each page to update the user’s last visit time.
  3. Create a PHP script to count the number of users online. This script will query the database for the number of users who have visited the website in the recent time period, and then output the results.
  4. Display the number of online users in the appropriate location.

Below is a simple example code:

// 连接数据库
$conn = mysqli_connect("localhost", "username", "password", "database");

// 更新用户最后访问时间
$userId = $_SESSION['userId']; // 假设你有用户ID保存在session中
$currentTime = time();
$query = "UPDATE online_users SET last_visit = $currentTime WHERE user_id = $userId";
mysqli_query($conn, $query);

// 统计在线人数
$onlineTime = 60; // 假设在线时间为60秒内的用户为在线用户
$thresholdTime = $currentTime - $onlineTime;
$query = "SELECT COUNT(*) FROM online_users WHERE last_visit > $thresholdTime";
$result = mysqli_query($conn, $query);
$onlineUsers = mysqli_fetch_row($result)[0];

// 显示在线人数
echo "在线人数:$onlineUsers";

Please note that this is just a simple example code and may need to be modified and optimized according to specific requirements. Additionally, this method has some limitations, such as not being able to accurately count the real-time online users and only being able to estimate.

bannerAds