本文提供兩種 PHP 計數器實作模式:直接在 PHP 頁面輸出文字、以及輸出 JavaScript 供靜態 HTML 引入,適合不同應用場景。
適用於 .php 檔案直接嵌入計數器顯示。
<?php
$countfile = "num.txt";
if (($fp = fopen($countfile, "r+")) == false) {
printf("開啟檔案 %s 失敗!", $countfile);
exit;
} else {
$count = fread($fp, 10);
$count = $count + 1;
fclose($fp);
$fp = fopen($countfile, "w+");
fwrite($fp, $count);
fclose($fp);
// 直接輸出文字
echo '您好,您是第 '. $count .' 位訪客';
}
?>
適用於靜態 .html 頁面,或需跨頁面共用計數器。
<?php
$countfile = "num.txt";
if (($fp = fopen($countfile, "r+")) == false) {
printf("開啟檔案 %s 失敗!", $countfile);
exit;
} else {
$count = fread($fp, 10);
$count = $count + 1;
fclose($fp);
$fp = fopen($countfile, "w+");
fwrite($fp, $count);
fclose($fp);
// 輸出 JavaScript document.write
echo 'document.write("'.$count.'")';
}
?>
儲存為 FileCount.php,同目錄建立 num.txt。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>訪客計數示範</title>
</head>
<body>
<div class="counter">
目前訪客人數:<script src="FileCount.php"></script>
</div>
</body>
</html>
| 特性 | 直接 PHP 輸出 | JS 輸出模式 |
|---|---|---|
| 適用檔案類型 | .php | .html / .php 皆可 |
| 頁面快取友善度 | 低(每次動態產生) | 高(HTML 可快取,JS 獨立請求) |
| 跨頁面共用 | 需 include | 多頁面引入同一 JS 即可 |
| 並發安全性 | 相同風險 | 相同風險 |
| SEO 影響 | 內容可被爬蟲讀取 | 需搜尋引擎支援 JS 渲染 |
<?php
$countfile = "num.txt";
// 使用檔案鎖防止並發衝突
$fp = fopen($countfile, "c+"); // c+ 模式:開啟讀寫,不存在則建立,指標在開頭
if (flock($fp, LOCK_EX)) { // 獨佔鎖
$count = (int)fread($fp, 20);
$count++;
ftruncate($fp, 0); // 清空檔案
rewind($fp); // 指標歸零
fwrite($fp, $count);
fflush($fp); // 強制寫入磁碟
flock($fp, LOCK_UN); // 釋放鎖
}
fclose($fp);
// 判斷輸出模式(可透過 $_GET['format'] 切換)
$format = isset($_GET['format']) ? $_GET['format'] : 'text';
if ($format === 'js') {
header('Content-Type: application/javascript; charset=UTF-8');
echo 'document.write("'.$count.'");';
} else {
echo '您好,您是第 '. $count .' 位訪客';
}
?>
num.txt 檔案存在且可讀寫flock)防止並發問題