int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
相當於依次呼叫 fopen()、fwrite()、fclose(),PHP 5.0+ 內建。
| 參數 | 說明 |
|---|---|
| filename | 文件路徑,不存在則自動建立(需目錄可寫)。 |
| data | 要寫入的資料:字串、陣列(一維,相當於 join('', $array))、資源流(PHP 5.1+)。 |
| flags | 位元組合:FILE_USE_INCLUDE_PATH、FILE_APPEND(追加)、LOCK_EX(獨佔鎖)。 |
| context | 流上下文資源(如 FTP/HTTP 選項)。 |
<?php
$contents = "這是使用 file_put_contents 寫入的內容";
$contents2 = ["這是使用", "file_put_contents", "命令寫入的內容"]; // 一維陣列
file_put_contents("html/cache.txt", $contents);
file_put_contents("html/cache2.txt", $contents2); // 自動 join('')
?>
注意:若文件名拼寫錯誤(如 caceh.txt),會在當前目錄建立新文件,原目標文件不變更。
<?php
$log = date("Y-m-d H:i:s") . " - 用戶登入\n";
file_put_contents("logs/access.log", $log, FILE_APPEND | LOCK_EX);
?>
<?php
$src = fopen('https://example.com/image.jpg', 'r');
file_put_contents('local.jpg', $src); // 相當於 stream_copy_to_stream()
fclose($src);
?>
<?php
$opts = ['ftp' => ['overwrite' => true]];
$ctx = stream_context_create($opts);
file_put_contents('ftp://user:pass@server/path/file.txt', $data, 0, $ctx);
?>
| 維度 | 手動三步 | file_put_contents() |
|---|---|---|
| 代碼行數 | 5-8 行 | 1 行 |
| 錯誤處理 | 需分別檢查每步返回值 | 僅檢查最終返回值(false 失敗) |
| 鎖機制 | 需手動 flock() | 旗標 LOCK_EX 一步到位 |
| 資源流支援 | 手動 stream_copy_to_stream() | 直接接受資源作為 $data |
| 性能 | 可控制緩衝大小 | 內部優化,通常更快 |
| 適用場景 | 複雜邏輯、分段寫入、需中間處理 | 簡單整體寫入、日誌、快取、下載儲存 |
false(需用 === false 判斷)。