HTML 無法直接執行伺服器邏輯。傳統做法:<script src="counter.php"> 讓 PHP 輸出 JavaScript 代碼,瀏覽器執行該 JS 將資料寫入頁面。這是早期「AJAX」前身 — **JSONP 模式**的前身。
<?php
$countFile = 'count.txt';
// 讀取或初始化
$count = 0;
if (file_exists($countFile)) {
$count = (int)file_get_contents($countFile);
}
$count++;
// 寫回 (簡易版,生產環境需加檔案鎖 flock)
file_put_contents($countFile, $count, LOCK_EX);
// 輸出 JavaScript 代碼
header('Content-Type: application/javascript; charset=UTF-8');
echo "document.write('$count');";
// 或現代寫法:回傳 JSON,前端 fetch 處理
// echo json_encode(['count' => $count]);
?>
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>訪客計數器</title>
</head>
<body>
您好,您是第 載入中... 位訪客
<!-- 傳統方式:PHP 直接輸出 JS -->
<script src="counter.php"></script>
<!-- 現代方式:fetch API (推薦) -->
<script>
// fetch('counter.php?format=json')
// .then(r => r.json())
// .then(d => document.getElementById('counter').textContent = d.count);
</script>
</body>
</html>
| 技術點 | 說明 |
|---|---|
<script src="xxx.php"> | 瀏覽器將 PHP 回應視為 JS 執行。PHP 需輸出合法 JS 語句 (如 document.write()、變數賦值、函式呼叫)。 |
| 同源策略 | 此法不受同源限制,可跨域載入 (JSONP 原理)。但**無法攜帶 Cookie/認證**,且**僅限 GET 請求**。 |
| 快取問題 | 瀏覽器會快取 .js/.php 回應。需加 header('Cache-Control: no-store') 或 URL 附加時間戳 ?t=Date.now()。 |
| 錯誤處理 | PHP 錯誤會輸出 HTML 錯誤頁,導致 JS 語法錯誤。生產環境需 try-catch 並輸出 console.error() 或預設值。 |
| 安全性 | **極度危險**:若參數未驗證直接拼入 JS 字串,極易造成 XSS。現代專案**嚴禁**此模式,改用 fetch() + JSON + CSP。 |
// counter.php (現代)
header('Content-Type: application/json');
echo json_encode(['count' => $count, 'timestamp' => time()]);
// index.html
fetch('counter.php')
.then(r => { if (!r.ok) throw new Error('Network'); return r.json(); })
.then(d => document.getElementById('counter').textContent = d.count)
.catch(e => console.error('計數器載入失敗', e));
原文提到的「Session 驗證」在純 HTML 頁面實作方式:
HttpOnly; Secure; SameSite=Lax Cookie。fetch('/api/user/me', {credentials: 'include'}) 自動攜帶 Cookie。**查詢字串傳遞參數** (如 ?userId=123) 仍是靜態頁面獲取動態資料的常用手段,配合 URLSearchParams 解析。