萬盛學電腦網

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

PHP 線上人數統計兩大方案:AltaVista 反向連結法與 MySQL Session 表法

前言

統計當前在線人數有多種實作方式。本文分析兩種經典方案:搜尋引擎反向連結法 (已過時) 與資料庫 Session 表法 (經典實作),並提供現代化的 Redis 方案。

方案一:AltaVista 反向連結法 (歷史參考)

原理: 查詢搜尋引擎索引中指向本站的連結數,作為「關注度」指標。

現狀: AltaVista 已關閉,Google/Bing 亦無公開此 API。**此方案已不可用**,僅供演算法歷史參考。

原始邏輯重構

<?php
// 歷史參考代碼,實際不可用
function getAltavistaLinkCount(string $url): int {
    $encoded = rawurlencode($url);
    $apiUrl = "https://www.altavista.com/cgi-bin/query?kl=XX&pg=q&text=yes&q=link:$encoded&search=Search";
    
    $content = @file_get_contents($apiUrl);
    if (!$content) return 0;
    
    // 解析 "About X pages found"
    if (preg_match('/About\s+([\d,]+)\s+pages?\s+found/i', $content, $m)) {
        return (int)str_replace(',', '', $m[1]);
    }
    if (str_contains($content, 'no document matching')) return 0;
    return 0;
}
?>

方案二:MySQL 臨時表法 (經典實作)

在資料庫建立線上用戶表,定期清理過期記錄。

資料表結構

CREATE TABLE `online_users` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `ip` VARBINARY(16) NOT NULL COMMENT 'IPv4: 4 bytes, IPv6: 16 bytes',
    `user_id` INT UNSIGNED NULL COMMENT '登入用戶 ID',
    `last_active` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `user_agent` VARCHAR(255) DEFAULT NULL,
    `current_url` VARCHAR(500) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_ip` (`ip`),
    KEY `idx_last_active` (`last_active`),
    KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

核心邏輯類別

<?php
class OnlineCounter {
    private PDO $pdo;
    private int $timeoutSeconds; // 判定在線閾值 (秒)
    
    public function __construct(PDO $pdo, int $timeoutSeconds = 180) {
        $this->pdo = $pdo;
        $this->timeoutSeconds = $timeoutSeconds;
    }
    
    /** 記錄用戶活動 */
    public function recordActivity(?int $userId = null): void {
        $ip = $this->getClientIp();
        $now = date('Y-m-d H:i:s');
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        
        // UPSERT: 新增或更新最後活動時間
        $sql = <<pdo->prepare($sql);
        $stmt->execute([
            $ip,
            $userId,
            $now,
            $ua,
            $uri,
        ]);
    }
    
    /** 取得當前在線人數 */
    public function getOnlineCount(): int {
        $cutoff = date('Y-m-d H:i:s', time() - $this->timeoutSeconds);
        $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM online_users WHERE last_active >= ?');
        $stmt->execute([$cutoff]);
        return (int)$stmt->fetchColumn();
    }
    
    /** 取得在線用戶詳情 */
    public function getOnlineUsers(int $limit = 100): array {
        $cutoff = date('Y-m-d H:i:s', time() - $this->timeoutSeconds);
        $stmt = $this->pdo->prepare(
            'SELECT ip, user_id, last_active, current_url FROM online_users 
             WHERE last_active >= ? ORDER BY last_active DESC LIMIT ?'
        );
        $stmt->execute([$cutoff, $limit]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /** 清理過期記錄 (建議由排程任務每分鐘執行) */
    public function cleanup(): int {
        $cutoff = date('Y-m-d H:i:s', time() - $this->timeoutSeconds);
        $stmt = $this->pdo->prepare('DELETE FROM online_users WHERE last_active < ?');
        $stmt->execute([$cutoff]);
        return $stmt->rowCount();
    }
    
    private function getClientIp(): string {
        // 支援 IPv6 與代理
        $headers = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
        foreach ($headers as $header) {
            if (!empty($_SERVER[$header])) {
                $ips = explode(',', $_SERVER[$header]);
                $ip = trim($ips[0]);
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    return inet_pton($ip); // 轉二進位儲存
                }
            }
        }
        return inet_pton('127.0.0.1');
    }
}

// 使用方式:每個頁面引入
require_once 'OnlineCounter.php';
$counter = new OnlineCounter($pdo, 180); // 3 分鐘閾值
$counter->recordActivity($currentUserId ?? null);
// 顯示人數
echo "線上人數: " . $counter->getOnlineCount();
?>

方案三:Redis 高效能方案 (現代標準)

利用 Redis 集合 (Set) + 過期時間,效能極佳、自動清理。

核心實作

<?php
class RedisOnlineCounter {
    private Redis $redis;
    private string $keyPrefix = 'online:';
    private int $ttl = 180; // 秒
    
    public function __construct(Redis $redis, int $ttl = 180) {
        $this->redis = $redis;
        $this->ttl = $ttl;
    }
    
    public function recordActivity(string $identifier): void {
        $key = $this->keyPrefix . date('Y-m-d:H:i'); // 分鐘級桶
        // 使用 Sorted Set: member=identifier, score=timestamp
        $this->redis->zAdd($key, time(), $identifier);
        $this->redis->expire($key, $this->ttl + 60); // 稍長於閾值
        
        // 全域在線集合 (可選)
        $this->redis->zAdd($this->keyPrefix . 'global', time(), $identifier);
        $this->redis->expire($this->keyPrefix . 'global', $this->ttl + 60);
    }
    
    public function getOnlineCount(int $minutes = 3): int {
        $now = time();
        $minScore = $now - ($minutes * 60);
        return $this->redis->zCount($this->keyPrefix . 'global', $minScore, $now);
    }
    
    public function getOnlineUsers(int $minutes = 3, int $limit = 100): array {
        $now = time();
        $minScore = $now - ($minutes * 60);
        // ZREVRANGEBYSCORE 取最新
        return $this->redis->zRevRangeByScore($this->keyPrefix . 'global', $now, $minScore, ['LIMIT' => [0, $limit]]);
    }
    
    // 靜態方法:快速單次使用
    public static function quickCount(Redis $redis, string $pageKey, int $ttl = 180): int {
        $key = "page_online:$pageKey";
        $id = session_id() ?: $_SERVER['REMOTE_ADDR'];
        $redis->zAdd($key, time(), $id);
        $redis->expire($key, $ttl);
        return $redis->zCount($key, time() - $ttl, time());
    }
}

// 使用
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$counter = new RedisOnlineCounter($redis);
$counter->recordActivity(session_id() ?: $_SERVER['REMOTE_ADDR']);
echo "線上: " . $counter->getOnlineCount();
?>

三方案比較

維度AltaVista 反向連結MySQL Session 表Redis Sorted Set
可用性❌ 已失效✅ 穩定✅ 極佳
即時性天級延遲秒級毫秒級
效能外部請求慢中等 (磁碟 I/O)極高 (記憶體)
資料豐富度僅連結數IP、用戶、URL、UA同 MySQL + 更快
維護成本無 (但不可用)需定期清理自動過期、無維護
擴展性不可擴展受限於 DB 連線數叢集原生支援

生產環境建議架構

<?php
// 介面定義
interface OnlineCounterInterface {
    public function recordActivity(string $identifier): void;
    public function getOnlineCount(int $minutes = 3): int;
}

// 工廠模式切換實作
class OnlineCounterFactory {
    public static function create(PDO $pdo = null, Redis $redis = null): OnlineCounterInterface {
        if ($redis) {
            return new RedisOnlineCounter($redis);
        }
        return new MySqlOnlineCounter($pdo); // 實作同上 MySQL 版
    }
}

// 使用
$counter = OnlineCounterFactory::create(pdo: $pdo, redis: $redis);
$counter->recordActivity($userId ?? session_id());
echo $counter->getOnlineCount();

擴展:顯示在地圖/列表

<?php
// 取得在線用戶地理位置 (需 GeoIP)
$users = $counter->getOnlineUsers(5, 50);
foreach ($users as $user) {
    $ip = inet_ntop($user['ip']); // 二進位轉字串
    $geo = geoip_record_by_name($ip); // 需安裝 geoip 擴展
    // 顯示國家/城市標記
}
?>
copyright © 萬盛學電腦網 all rights reserved