簡單實用的網站計數器,使用文字檔儲存造訪次數。核心運用 file_get_contents() 讀取、fopen()/fwrite()/fclose() 寫入,並封裝為類別結構。
<?php
class Sit_count {
public $FileName = 'count.txt';
function Count_add() {
if (file_exists($this->FileName)) {
// 讀取現有計數
$Temp = file_get_contents($this->FileName);
$Total = (int)$Temp + 1; // 強制轉整數避免字串相加
echo $Total;
// 寫入新計數
$T = fopen($this->FileName, 'w');
fwrite($T, $Total);
fclose($T);
} else {
echo '! file_exists';
}
}
}
$tp = new Sit_count;
$tp->Count_add();
?>
file_exists() 避免讀取不存在檔案產生警告file_get_contents() 一次讀取整個檔案到字串(int)$Temp 確保數值運算正確(文字檔讀出為字串)fopen(..., 'w') 以寫入模式開啟,會清空原內容並重寫fclose() 關閉檔案控制代碼,確保資料寫入磁碟count.txt 檔案,初始內容為 0chmod 666 count.txt 或設定目錄擁有者)<?php
class SitCountImproved {
private $file = 'count.txt';
public function increment(): int {
$fp = fopen($this->file, 'c+'); // 開啟讀寫,不存在則建立
if (!$fp) {
throw new RuntimeException("無法開啟計數器檔案");
}
// 獨佔鎖定(阻塞直到取得鎖)
if (flock($fp, LOCK_EX)) {
$count = (int)fread($fp, filesize($this->file) ?: 1) + 1;
ftruncate($fp, 0); // 清空檔案
rewind($fp); // 指標回開頭
fwrite($fp, $count); // 寫入新值
fflush($fp); // 刷新緩衝區
flock($fp, LOCK_UN); // 釋放鎖
}
fclose($fp);
return $count;
}
}
$counter = new SitCountImproved();
echo $counter->increment();
?>
flock() 檔案鎖定防止競態條件;c+ 模式自動建立檔案;ftruncate()+rewind() 確保完整覆寫;例外處理增強健壯性。