在网站目录data文件夹新建online_stats文件夹,online_stats文件夹里面新建一个online.php文件,复制以下代码,data文件夹权限改为755应用到子目录。
<?php
$timeout = 300;
$logFile = __DIR__ . '/.online_log';
try {
// 检测必要参数是否存在
$isWebRequest = isset($_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);
// 读取现有数据
$activeUsers = file_exists($logFile)
? json_decode(file_get_contents($logFile), true)
: [];
// 清理过期记录
$currentTime = time();
foreach($activeUsers as $key => $timestamp) {
if($currentTime - $timestamp > $timeout) {
unset($activeUsers[$key]);
}
}
// 仅在Web请求时更新记录
if($isWebRequest) {
$Hash = hash('sha256', $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
$activeUsers[$Hash] = $currentTime;
}
// 保存数据(原子操作)
file_put_contents($logFile, json_encode($activeUsers), LOCK_EX);
// 返回在线人数
echo count($activeUsers);
} catch (Exception $e) {
error_log("Online Counter Error: " . $e->getMessage());
echo "0";
}
?>
/themes/default文件夹找到前端底部footer.html中的
<div id="onlineCounter">当前在线:加载中...</div>
<script>
// 定时更新(每60秒)
function updateCounter() {
fetch('/data/online_stats/online.php')
.then(response => response.text())
.then(count => {
document.getElementById('onlineCounter').innerHTML =
`当前在线:${count}人`;
})
.catch(() => console.log('统计服务不可用'));
}
// 页面加载时立即执行
updateCounter();
// 设置定时器
setInterval(updateCounter, 60000);
</script>
至此35dir底部加一个当前实时在线人数的功能就实现了