函數原型
fopen(string $filename, string $mode, bool $use_include_path = false, ?resource $context = null): resource|false
模式參數完整對照
| 模式 | 讀/寫 | 指標位置 | 截斷檔案 | 建立檔案 | 備註 |
| r | 唯讀 | 開頭 | 否 | 否 | 檔案必須存在 |
| r+ | 讀寫 | 開頭 | 否 | 否 | |
| w | 唯寫 | 開頭 | 是 | 是 | 清空現有內容 |
| w+ | 讀寫 | 開頭 | 是 | 是 | |
| a | 唯寫 | 結尾 | 否 | 是 | 追加模式 |
| a+ | 讀寫 | 結尾 | 否 | 是 | |
| x | 唯寫 | 開頭 | 否 | 是 | 排他建立,存在則失敗 (PHP 4.3.2+) |
| x+ | 讀寫 | 開頭 | 否 | 是 | 排他建立 |
| c | 唯寫 | 開頭 | 否 | 是 | 不截斷,不排他 (PHP 5.2.6+) |
| c+ | 讀寫 | 開頭 | 否 | 是 | |
串流封裝協議 (Wrappers)
- `file://`:本地檔案 (預設)
- `https://`、`https://`:HTTP 請求 (需 `allow_url_fopen=On`)
- `ftp://`、`ftps://`:FTP
- `php://input`、`php://output`、`php://memory`、`php://temp`
- `data://`:Data URI
- `zlib://`、`compress.zlib://`:壓縮串流
- 自定義:`stream_wrapper_register()`
跨平台換行符處理
| 作業系統 | 換行符 | PHP 模式標記 |
| Unix/Linux/macOS | LF (\n) | `b` (二進制、不轉換) |
| Windows | CRLF (\r\n) | `t` (文字模式、自動 \n→\r\n) |
| Classic Mac | CR (\r) | — |
最佳實踐:總是顯式指定 `b` 標記 (如 `rb`、`wb`、`ab`),確保跨平台行為一致,避免圖片損壞、CSV 解析錯誤。
Context 參數進階用法
<?php
// HTTP POST 請求
$ctx = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query(['foo' => 'bar']),
'timeout' => 10,
]
]);
$fp = fopen('https://api.example.com/endpoint', 'rb', false, $ctx);
$response = stream_get_contents($fp);
fclose($fp);
// 限制讀取大小
$ctx = stream_context_create(['php' => ['memory_limit' => '16M']]);
$fp = fopen('large.log', 'rb', false, $ctx);
?>
常見錯誤與排查
- Permission denied:檢查檔案/目錄權限、SELinux、open_basedir 限制
- No such file or directory:相對路徑問題,使用 `__DIR__` 或絕對路徑
- HTTP wrapper does not support writeable connections:HTTP 只支援讀取,寫入需用 cURL 或 `fopen('php://output')` 配合 context