首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP fopen 檔案讀寫實戰:模式選擇、資源管理、計數器與 robots.txt 編輯器

     編輯:PHP 相關知識

fopen 模式完整對照

模式讀/寫指標建立截斷失敗行為
r讀開頭否否false
r+讀/寫開頭否否false
w寫開頭是是false
w+讀/寫開頭是是false
a寫結尾是否false
a+讀/寫結尾是否false
x寫開頭唯不存在否false
x+讀/寫開頭唯不存在否false

資源管理最佳實踐

<?php
// 手動管理
$fp = fopen('data.txt', 'r');
if ($fp) {
    try {
        // 讀取邏輯
    } finally {
        fclose($fp); // 確保關閉
    }
}

// PHP 8.1+ 可用 fclose 自動管理(但 fopen 無支援)
// 建議封裝函數
function withFile(string $path, string $mode, callable $callback) {
    $fp = fopen($path, $mode);
    if (!$fp) throw new RuntimeException("無法開啟 $path");
    try {
        return $callback($fp);
    } finally {
        fclose($fp);
    }
}

// 使用
$content = withFile('data.txt', 'r', fn($fp) => stream_get_contents($fp));
?>

實戰案例 1:檔案計數器

<?php
function hitCounter(string $file = 'counter.txt'): int {
    $count = 0;
    if (file_exists($file)) {
        $count = (int) file_get_contents($file);
    }
    $count++;
    file_put_contents($file, $count, LOCK_EX); // 獨佔鎖防並發
    return $count;
}
echo "您是第 " . hitCounter() . " 位訪客";
?>

實戰案例 2:robots.txt 線上編輯器

<?php
// robots_editor.php
$file = __DIR__ . '/robots.txt';
$action = $_GET['action'] ?? 'view';
$message = '';

if ($action === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $content = $_POST['content'] ?? '';
    if (file_put_contents($file, $content, LOCK_EX) !== false) {
        $message = '儲存成功';
    } else {
        $message = '儲存失敗';
    }
}

$content = file_exists($file) ? file_get_contents($file) : '';
?>
<!DOCTYPE html>
<html><head><title>robots.txt 編輯器</title></head><body>
    <h1>robots.txt</h1>
    


取消
</body></html>

大檔案逐行處理

<?php
function processLargeFile(string $path, callable $lineHandler): void {
    $fp = fopen($path, 'r');
    if (!$fp) throw new RuntimeException("無法開啟 $path");
    while (($line = fgets($fp)) !== false) {
        $lineHandler(rtrim($line, "\r\n"));
    }
    fclose($fp);
}

// 使用
processLargeFile('huge.log', function($line) {
    if (str_contains($line, 'ERROR')) {
        error_log($line);
    }
});
?>

鎖機制與並發

  • LOCK_EX 獨佔鎖(寫入時)
  • LOCK_SH 共享鎖(讀取時)
  • file_put_contents(..., LOCK_EX) 內建支援
  • flock($fp, LOCK_EX) 手動控制
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved