萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP + jQuery 實時顯示網站在線人數

實時展示網站在線用戶數能增強社區氛圍與信任感。本文實現一個基於 PHP Session + 文件/Redis 存儲、jQuery AJAX 輪詢前端展示的輕量級在線人數統計系統,支援多頁面嵌入、動畫數字變化。

核心原理

  1. 用戶訪問任意頁面 → PHP 記錄 Session ID + 最後活動時間到存儲。
  2. 定期清理超時(如 5 分鐘無活動)的 Session 記錄。
  3. 統計當前有效 Session 數 = 在線人數。
  4. 前端 jQuery 定時 AJAX 獲取數字,配合 animate() 平滑過渡顯示。

後端實現 (File 存儲版,零依賴)

<?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>

進階:Redis 存儲版(高併發、多服務器)

<?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;
  • 側邊欄 Widget:結合「今日訪問量、總訪問量」組成站長統計面板。
  • 用戶列表頁:滑鼠懸停顯示最近活躍用戶頭像(需 API 返回前 N 個)。

準確性提升

  1. Heartbeat 機制:前端每 30 秒發送 online.php?act=heartbeat 更新活躍時間,比依賴頁面加載更準確。
  2. WebSocket 推送:建立長連接,服務器主動推送人數變化,實現真正實時、零延遲。
  3. 區分用戶/遊客:已登錄用戶用 user_id,遊客用 session_id,分別統計。
  4. 排除爬蟲:UA 特徵、IP 信譽庫過濾已知爬蟲,不計入在線人數。

此方案從零依賴文件版到 Redis 分佈式版全覆蓋,前端動畫效果優雅,可直接集成至任意 PHP 項目,瞬間提升網站「活躍感」。

copyright © 萬盛學電腦網 all rights reserved