以文字檔 count.txt 記錄 時間戳\tIP\n,每次請求:
<?php
function getIpAddress() {
if (getenv('HTTP_CLIENT_IP')) return getenv('HTTP_CLIENT_IP');
if (getenv('HTTP_X_FORWARDED_FOR')) return getenv('HTTP_X_FORWARDED_FOR');
if (getenv('REMOTE_ADDR')) return getenv('REMOTE_ADDR');
return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}
function writeover($filename, $data, $method = 'w', $chmod = 0) {
$handle = fopen($filename, $method);
if (!$handle) die("檔案開啟失敗");
flock($handle, LOCK_EX);
fwrite($handle, $data);
flock($handle, LOCK_UN);
fclose($handle);
if ($chmod) @chmod($filename, 0777);
}
function count_online_num($time, $ip) {
$file = './count.txt';
$gap = 900; // 15 分鐘
if (!file_exists($file)) {
writeover($file, "$time\t$ip\n", 'w', 1);
return 1;
}
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$flag = 0;
foreach ($lines as $key => $line) {
list($when, $storedIp) = explode("\t", $line, 2);
if ($storedIp === $ip) {
$lines[$key] = "$time\t$ip";
$flag = 1;
} elseif ($time - $when > $gap) {
unset($lines[$key]); // 過期移除
}
}
if ($flag === 0) {
$lines[] = "$time\t$ip";
}
writeover($file, implode("\n", $lines) . "\n", 'w');
return count($lines);
}
$time = time();
$ip = getIpAddress();
echo count_online_num($time, $ip);
?>
ZADD online:{timestamp} {ip},ZREMRANGEBYSCORE 清理過期,ZCARD 取得人數,效能更佳且天然支援分散式。flock 非阻塞模式或分檔案分片降低鎖爭用。X-Forwarded-For),避免偽造。