使用者因斷網、當機等非正常方式離開,導致在線名單殘留「僵屍帳號」,顯示人數不準。傳統單一檔案鎖定法在高併發下效能差、易死鎖。
useronline/ 子目錄專存在線資料touch 更新該檔案修改時間stat() 系統呼叫極快touch()、unlink()、scandir()、filemtime() 基礎函式// 使用者心跳更新
$user_file = "useronline/$username";
touch($user_file); // 建立或更新修改時間
// 後台清理腳本(cron 每 5 分鐘執行)
$dir = 'useronline/';
$now = time();
$timeout = 300; // 5 分鐘
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file === '.' || $file === '..') continue;
$path = $dir . $file;
if ($now - filemtime($path) > $timeout) {
unlink($path); // 判定為異常離線,移除
}
}
closedir($handle);
}
$online_users = array_diff(scandir($dir), ['.', '..']);
$online_count = count($online_users);
適合中小型聊天室、即時客服系統、線上遊戲大廳。極大規模(十萬級併發)建議改用 Redis Set + TTL 或 GatewayWorker 等長連接框架。