寫法一:極簡函數 countx()
function countx($file = "count.dat") {
if(file_exists($file)) {
$fp = fopen($file, "r");
$numx = fgets($fp, 10);
fclose($fp);
$numx++;
} else {
$numx = 1;
}
file_put_contents($file, $numx);
echo $numx;
}
// 呼叫
countx();
寫法二:系統指令操作檔案(不推薦,有注入風險)
$counterfile = "balong.txt";
function displaycounter($counterfile) {
$fp = fopen($counterfile, "rw");
$num = fgets($fp, 5);
$num += 1;
print "您是第 $num 個看巴泷計數器的家伙";
exec("rm -rf " . escapeshellarg($counterfile));
exec("echo $num > " . escapeshellarg($counterfile));
}
if(!file_exists($counterfile)) exec("echo 0 > " . escapeshellarg($counterfile));
displaycounter($counterfile);
寫法三:同上但不同檔名(示範多頁面獨立計數)
$counterfile = "www.bkjia.com.txt";
// 其餘邏輯同寫法二
最佳實踐建議
- 使用
file_put_contents + file_get_contents 或 fopen + flock 確保並發安全。
- 避免
exec,若必須用請嚴格 escapeshellarg。
- 高流量網站建議改用 Redis/Memcached 原子增量,定期持久化至資料庫。
- 計數器檔案置於公開目錄外,防止被直接下載或竄改。