PHP Count Online Users: Session Method
To monitor the number of users online on a website, you can use PHP sessions. Here is a simple example code:
// 开启session
session_start();
// 设置session变量来保存在线人数
if(!isset($_SESSION['online_users'])) {
$_SESSION['online_users'] = 1;
} else {
$_SESSION['online_users']++;
}
// 获取在线人数
$online_users = $_SESSION['online_users'];
// 输出在线人数
echo "当前在线人数: $online_users";
// 在页面底部可以添加一个定时刷新功能,实时更新在线人数
echo '<meta http-equiv="refresh" content="60">'; // 每60秒自动刷新页面
In this example, we begin by using the session_start() function to start a session and then use the $_SESSION[‘online_users’] variable to keep track of the number of users online. Each time a user visits the page, the online user count increases by 1. Finally, we use echo to display the current number of online users. Additionally, we have added a timed refresh feature at the bottom of the page that automatically refreshes every 60 seconds to provide real-time updates on the online user count.
It is important to note that since sessions are based on cookies, if a user closes their browser or clears cookies, the session will be reset and the online user count will restart.