以下是一个简单的PHP在线人数统计的开源代码示例:
index.php:
<?php
session_start();
// 更新在线用户数
function updateOnlineUsers() {
$timeout = 300; // 在线超时时间(秒)
$file = 'online_users.txt'; // 保存在线用户的文件
if (file_exists($file)) {
$users = unserialize(file_get_contents($file));
$updatedUsers = array();
foreach ($users as $user) {
if (time() - $user['timestamp'] < $timeout) {
$updatedUsers[] = $user;
}
}
// 添加当前用户到在线用户列表
$updatedUsers[] = array(
'id' => session_id(),
'ip' => $_SERVER['REMOTE_ADDR'],
'timestamp' => time()
);
file_put_contents($file, serialize($updatedUsers));
} else {
// 创建新的在线用户列表文件并添加当前用户
$users = array(
array(
'id' => session_id(),
'ip' => $_SERVER['REMOTE_ADDR'],
'timestamp' => time()
)
);
file_put_contents($file, serialize($users));
}
}
// 获取在线用户数
function getOnlineUsersCount() {
$timeout = 300; // 在线超时时间(秒)
$file = 'online_users.txt'; // 保存在线用户的文件
if (file_exists($file)) {
$users = unserialize(file_get_contents($file));
$count = 0;
foreach ($users as $user) {
if (time() - $user['timestamp'] < $timeout) {
$count++;
}
}
return $count;
}
return 0;
}
// 更新在线用户数
updateOnlineUsers();
// 获取在线用户数
$onlineUsersCount = getOnlineUsersCount();
?>
<!DOCTYPE html>
<html>
<head>
<title>在线人数统计</title>
</head>
<body>
<h1>当前在线人数:<?php echo $onlineUsersCount; ?></h1>
</body>
</html>
使用方法:
online_users.txt
的空文本文件,并确保该文件可写入;index.php
文件;index.php
文件上传到你的PHP服务器;index.php
文件,即可看到当前在线人数。注意事项:
session
来识别用户,确保你的PHP服务器已启用session
;Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站