萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 文字檔計數器實作:file_get_contents 與 fopen/fwrite 讀寫應用

簡單實用的網站計數器,使用文字檔儲存造訪次數。核心運用 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();
?>

關鍵步驟解析

  1. 檢查檔案存在:file_exists() 避免讀取不存在檔案產生警告
  2. 讀取內容:file_get_contents() 一次讀取整個檔案到字串
  3. 型別轉換:(int)$Temp 確保數值運算正確(文字檔讀出為字串)
  4. 寫入模式:fopen(..., 'w') 以寫入模式開啟,會清空原內容並重寫
  5. 資源釋放:fclose() 關閉檔案控制代碼,確保資料寫入磁碟

部署注意事項

  • 需手動建立 count.txt 檔案,初始內容為 0
  • 確保 PHP 程序對該檔案有讀寫權限(Linux 下通常需 chmod 666 count.txt 或設定目錄擁有者)
  • 高流量網站會有競態條件問題(並發讀寫導致計數遺漏),生產環境建議改用資料庫或 Redis 原子操作

進階改良版(含檔案鎖定)

<?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() 確保完整覆寫;例外處理增強健壯性。
copyright © 萬盛學電腦網 all rights reserved