file_put_contents() 將字符串、陣列或流資源一次性寫入文件,相當於 fopen()+fwrite()+fclose() 的原子封裝,是 PHP 5+ 寫入文件的標準方式。
int file_put_contents ( string $filename, mixed $data [, int $flags = 0 [, resource $context ]] )
implode(''))、流資源(自動 stream_copy_to_stream())。FILE_USE_INCLUDE_PATH:在 include_path 搜尋FILE_APPEND:追加模式(預設覆蓋)LOCK_EX:寫入期間獲取獨佔鎖(防併發衝突)FILE_TEXT / FILE_BINARY:編碼模式(PHP 6+)int)。FALSE。<?php
$file = 'people.txt';
$current = file_get_contents($file);
$current .= "John Smith\n";
file_put_contents($file, $current);
?>
<?php
$file = 'people.txt';
$person = "John Smith\n";
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
// 組合旗標:追加 + 獨佔鎖,防多進程數據交織
?>
關鍵點:LOCK_EX 確保寫入過程原子性,避免「讀取-修改-寫入」競態條件。但注意:LOCK_EX 僅鎖定文件指針,NFS 掛載下可能失效,極高併發建議用 Redis/資料庫。
<?php
$src = fopen('huge_export.csv', 'r');
file_put_contents('backup.csv', $src); // 內部自動 stream_copy_to_stream
fclose($src);
?>
file_put_contents("$file.tmp", $data) 成功後 rename("$file.tmp", $file),防止讀到半寫文件。mkdir(dirname($file), 0755, true) 遞歸建目錄。| 方式 | 適用場景 | 併發安全 | 備註 |
|---|---|---|---|
| file_put_contents() | 中小文件、日誌、配置 | 支援 LOCK_EX | 代碼最簡潔 |
| fopen('a')+fwrite() | 極大文件分塊寫入 | 需手動 flock() | 可控制緩衝區大小 |
| SplFileObject | 面向對象風格 | 支援 flock() | 可鏈式調用 |
| 臨時文件+rename | 關鍵配置、用戶數據 | 文件系統級原子 | 最安全,跨進程可見 |