fwrite() 將字串內容寫入檔案指標指向的位置,支援二進制安全寫入,是處理檔案輸出的基石函數。
int fwrite ( resource $handle, string $string [, int $length ] )
$handle:由 fopen() 回傳的檔案指標資源。$string:要寫入的資料。$length(可選):最大寫入位元組數。若指定,寫入達到該長度或字串結束時停止;且會忽略 magic_quotes_runtime 設定,斜線不會被剝離。FALSE。fopen() 時模式需加 'b'(如 'wb'、'ab'),否則換行符可能被轉換導致二進制資料損壞。is_writable() 確認檔案/目錄權限。=== FALSE 判斷失敗,避免寫入 0 位元組被誤判。fclose() 釋放資源、刷新緩衝區。<?php
$filename = 'test.txt';
$content = "新增的內容\n";
// 1. 確認檔案存在且可寫
if (!is_writable($filename)) {
die("檔案 {$filename} 不可寫");
}
// 2. 以追加模式開啟(二進制安全)
if (!$handle = fopen($filename, 'ab')) {
die("無法開啟檔案 {$filename}");
}
// 3. 寫入並嚴格檢查
if (fwrite($handle, $content) === FALSE) {
fclose($handle);
die("寫入檔案 {$filename} 失敗");
}
echo "成功寫入 {$filename}";
fclose($handle);
?>
<?php
$data = "這是一段很長的二進制資料...";
$handle = fopen('data.bin', 'wb');
// 僅寫入前 1024 位元組
fwrite($handle, $data, 1024);
fclose($handle);
?>
| 錯誤 | 後果 | 正確做法 |
|---|---|---|
| Windows 下 fopen 模式缺 'b' | 二進制檔案(圖片、PDF)損壞 | 一律使用 'wb'、'ab'、'rb' 等模式 |
| 未檢查 is_writable | 寫入靜默失敗、難以除錯 | 寫入前驗證權限 |
| 用 == FALSE 判斷 | 寫入 0 位元組被誤判為失敗 | 用 === FALSE 嚴格比對 |
| 忘記 fclose | 資源洩漏、資料留在緩衝區 | 配合 try/finally 或 defer 模式確保關閉 |
fwrite() 配合正確的 fopen() 模式、權限檢查、嚴格錯誤處理,即可可靠地完成文字與二進制檔案的寫入任務。現代專案建議封裝為檔案服務類,統一異常處理與日誌記錄。