在頁面嵌入 <img src="sitestat.php?url=...&userid=...">,瀏覽器自動發起 GET 請求載入圖片。PHP 端生成 1x1 透明 PNG 回應,同時記錄參數至日誌檔。此即 Beacon/Tracking Pixel 技術,不阻塞頁面渲染,支援跨域。
<img src="sitestat.php?url=www.domain.com&userid=1" width="1" height="1" alt="" />
<?php
// 1. 取得參數
$param = [
'url' => $_GET['url'] ?? '',
'userid' => $_GET['userid'] ?? 0,
'time' => date('Y-m-d H:i:s'),
'ip' => $_SERVER['REMOTE_ADDR'],
'ua' => $_SERVER['HTTP_USER_AGENT'],
'ref' => $_SERVER['HTTP_REFERER'] ?? ''
];
// 2. 寫入日誌 (JSON Lines 格式,易於後續分析)
$logLine = json_encode($param, JSON_UNESCAPED_UNICODE) . "\n";
file_put_contents('sitestat.log', $logLine, FILE_APPEND | LOCK_EX);
// 3. 回應 1x1 透明 PNG
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
$im = imagecreate(1, 1);
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127); // 完全透明
imagefill($im, 0, 0, $transparent);
imagepng($im);
imagedestroy($im);
?>
event(click/scroll)、page_id、session_id 等豐富維度。Referer、簽名防範偽造請求;日誌檔權限設為 600,防洩露。navigator.sendBeacon() (JS) 更可靠支援 POST、不阻塞卸載、無圖片偽裝需求。<img> Beacon 是極簡、相容性最佳的客戶端遙測手段。搭配 PHP GD 生成透明圖片、JSON Lines 日誌格式,即可快速建立輕量級訪問分析系統。現代專案建議漸進式遷移至 sendBeacon + 結構化事件收集平台。