實時展示網站在線用戶數能增強社區氛圍與信任感。本文實現一個基於 PHP Session + 文件/Redis 存儲、jQuery AJAX 輪詢前端展示的輕量級在線人數統計系統,支援多頁面嵌入、動畫數字變化。
animate() 平滑過渡顯示。<?php
// online.php - 統計接口 & 維護邏輯
header('Content-Type: application/json; charset=utf-8');
$action = $_GET['act'] ?? 'count';
$storeFile = __DIR__ . '/data/online_sessions.json';
$timeout = 300; // 5 分鐘無活動視為離線
// 確保存儲目錄存在
$dir = dirname($storeFile);
if (!is_dir($dir)) mkdir($dir, 0755, true);
// 載入現有數據
$sessions = [];
if (file_exists($storeFile)) {
$json = file_get_contents($storeFile);
$sessions = json_decode($json, true) ?: [];
}
$now = time();
$sessionId = session_id();
// 1. 更新/創建當前 Session 記錄
if ($action !== 'count') { // 非純統計請求時更新活躍時間
$sessions[$sessionId] = [
'last_active' => $now,
'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
'ua' => substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 100),
];
}
// 2. 清理過期 Session
$sessions = array_filter($sessions, fn($s) => ($now - $s['last_active']) < $timeout);
// 3. 保存(原子寫入)
$tmp = $storeFile . '.tmp';
file_put_contents($tmp, json_encode($sessions), LOCK_EX);
rename($tmp, $storeFile);
// 4. 返回結果
$count = count($sessions);
if (isset($_GET['jsonp'])) {
echo $_GET['jsonp'] . '(' . json_encode(['n' => $count]) . ')';
} else {
echo json_encode(['n' => $count, 'time' => $now]);
}
<!-- HTML 任意位置 -->
<div class="online-count">
當前在線:<span id="onlineNumber">0</span> 人
</div>
<!-- 引入 jQuery -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
(function($) {
var $num = $('#onlineNumber');
var apiUrl = 'online.php?jsonp=?'; // JSONP 跨域友好,同域可去掉 jsonp=?
// 動畫更新數字
function animateNumber(target) {
$({count: parseInt($num.text()) || 0}).animate({count: target}, {
duration: 500,
easing: 'swing',
step: function() {
$num.text(Math.floor(this.count).toLocaleString());
},
complete: function() {
$num.text(target.toLocaleString());
}
});
}
// 獲取並更新
function updateOnline() {
$.getJSON(apiUrl, function(data) {
if (data && typeof data.n === 'number') {
animateNumber(data.n);
}
}).fail(function() {
console.warn('在線人數獲取失敗');
});
}
// 初始加載 + 定時輪詢 (每 10 秒)
updateOnline();
setInterval(updateOnline, 10000);
// 頁面可見性變化時立即更新
document.addEventListener('visibilitychange', function() {
if (!document.hidden) updateOnline();
});
})(jQuery);
</script>
<?php
// online_redis.php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key = 'online:sessions';
$timeout = 300;
$sessionId = session_id();
$now = time();
// 使用 Sorted Set:Score = last_active, Member = session_id
// 更新當前會話
$redis->zAdd($key, $now, $sessionId);
// 設置過期時間(整個 Key),避免永久佔用內存
$redis->expire($key, $timeout + 60);
// 清理過期(ZREMRANGEBYSCORE)
$redis->zRemRangeByScore($key, 0, $now - $timeout);
// 統計
$count = $redis->zCard($key);
header('Content-Type: application/json');
echo json_encode(['n' => $count, 'time' => $now]);
position:fixed; bottom:10px; right:10px;online.php?act=heartbeat 更新活躍時間,比依賴頁面加載更準確。user_id,遊客用 session_id,分別統計。此方案從零依賴文件版到 Redis 分佈式版全覆蓋,前端動畫效果優雅,可直接集成至任意 PHP 項目,瞬間提升網站「活躍感」。