路徑資訊函數
| 函數 | 說明 | 範例 |
basename($path, $suffix='') | 取得檔名,可選移除尾綴 | `basename('/a/b.php', '.php')` → `b` |
dirname($path) | 取得目錄路徑 | `dirname('/a/b.php')` → `/a` |
pathinfo($path, $options) | 返回關聯陣列:dirname/basename/extension/filename | `pathinfo('/a/b.tar.gz')` → `['extension'=>'gz','filename'=>'b.tar']` |
realpath($path) | 解析絕對路徑(解析符號連結、相對路徑),不存在返回 false | `realpath('../config')` → `/var/www/config` |
檔案讀寫核心函數
高層級(一次性讀寫,適合中小檔案)
| 函數 | 說明 | 二進位安全 |
file_get_contents($file, $use_include_path, $context, $offset, $length) | 讀整個檔案為字串 | ✅ |
file_put_contents($file, $data, $flags, $context) | 寫字串到檔案,`FILE_APPEND` 追加,`LOCK_EX` 獨佔鎖 | ✅ |
file($file, $flags, $context) | 讀整個檔案為陣列(每行一元素) | ✅ |
readfile($file, $use_include_path, $context) | 直接輸出到標準輸出,返回位元組數,**不佔用 PHP 記憶體** | ✅ |
低層級(流操作,適合大檔案/精確控制)
<?php
$fp = fopen('large.log', 'rb'); // b: 二進位模式(Windows 必須)
if (!$fp) die('Open failed');
while (!feof($fp)) {
$line = fgets($fp, 8192); // 逐行讀取
// 處理 $line...
}
fclose($fp);
// 寫入
$fp = fopen('output.bin', 'wb');
fwrite($fp, $binaryData);
fclose($fp);
// 定位
fseek($fp, 0, SEEK_END); // 移至末尾
fseek($fp, -100, SEEK_END); // 倒數 100 位元組
ftell($fp); // 當前位置
// 截斷
ftruncate($fp, 1024); // 縮減/擴大到 1024 位元組
檔案屬性與狀態
| 函數 | 返回 | 備註 |
file_exists($path) | bool | 檔案/目錄皆可,緩存結果需 `clearstatcache()` |
is_file($path) / is_dir($path) / is_link($path) | bool | 類型判斷 |
is_readable($path) / is_writable($path) / is_executable($path) | bool | 權限檢查(受 open_basedir 影響) |
filesize($path) | int/false | 位元組數,**受 32 位系統 2GB 限制**,大檔用 `stat()` |
filemtime/atime/ctime($path) | int/false | 修改/訪問/狀態改變時間 (Unix timestamp) |
fileowner/group($path) | int/false | UID/GID |
fileperms($path) | int/false | 權限位元組,配合 `substr(sprintf('%o', $p), -4)` 顯示 |
filetype($path) | string | `file`/`dir`/`link`/`fifo`/`block`/`char`/`socket` |
stat($path) / fstat($fp) | array | 完整 stat 結構,含 inode、device、blocks 等 |
目錄操作
<?php
// 建立目錄(遞迴、權限)
mkdir('/path/to/dir', 0755, true);
// 刪除目錄(必須為空)
rmdir('/path/to/dir');
// 遞迴刪除目錄樹
function rrmdir(string $dir): bool {
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($items as $item) {
$item->isDir() ? rmdir($item->getPathname()) : unlink($item->getPathname());
}
return rmdir($dir);
}
// 掃描目錄
$files = scandir($dir); // 含 . ..
$files = glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE); // 模式匹配
// 迭代器模式(記憶體友好)
foreach (new DirectoryIterator($dir) as $file) {
if (!$file->isDot()) echo $file->getFilename() . "\n";
}
檔案鎖與併發控制
<?php
$fp = fopen('counter.txt', 'c+'); // 開啟/建立,指標在開頭
if (flock($fp, LOCK_EX)) { // 獨佔鎖 (阻塞)
$count = (int)fread($fp, 8192) + 1;
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, (string)$count);
flock($fp, LOCK_UN);
} else {
// 非阻塞嘗試
if (flock($fp, LOCK_EX | LOCK_NB)) { ... }
}
fclose($fp);
注意:`flock` 是**建議性鎖**,僅在同一進程/協作進程間生效。NFS/某些檔案系統可能不支援。跨進程強制鎖需 `fcntl` 或資料庫鎖。
臨時檔案與上傳處理
| 函數 | 用途 |
tmpfile() | 建立匿名臨時檔案(關閉/腳本結束自動刪除),返回資源 |
tempnam($dir, $prefix) | 建立唯一命名臨時檔案,返回路徑,**不自動刪除** |
move_uploaded_file($tmp, $dest) | **唯一安全**移動上傳檔案(驗證是 HTTP POST 上傳) |
is_uploaded_file($tmp) | 驗證是否為上傳檔案 |
串流封裝器
<?php
// 讀取壓縮檔
$content = file_get_contents('compress.zlib://large.log.gz');
// 寫入壓縮檔
file_put_contents('compress.zlib://output.gz', $data);
// 記憶體流(大字串當檔案操作)
$fp = fopen('php://memory', 'r+'); // 超過限制自動轉暫存檔
$fp = fopen('php://temp/maxmemory:1048576', 'r+'); // 1MB 後落盤
// 標準輸入輸出
$stdin = fopen('php://stdin', 'r');
$stdout = fopen('php://stdout', 'w');
$stderr = fopen('php://stderr', 'w');
// 過濾器鏈
$fp = fopen('php://filter/read=string.toupper|convert.iconv.utf-8.utf-16/resource=data.txt', 'r');
效能優化清單
- 大檔案用流:`fopen`/`fread`/`fwrite` 避免一次性載入記憶體
- 批量寫入用 `file_put_contents(..., FILE_APPEND | LOCK_EX)`:單次系統調用,原子追加
- 輸出檔案用 `readfile()` 或 `fpassthru()`:零拷貝到輸出緩衝
- 頻繁 `file_exists`/`is_file` 先 `clearstatcache(true, $path)`**:PHP 緩存 stat 結果,可能導致誤判
- 遞迴遍歷用 `RecursiveDirectoryIterator` + `RecursiveIteratorIterator`**:記憶體效率高、可過濾
- 大量小檔案考慮合併/資料庫/對象存儲**:inode 耗盡風險
錯誤處理模式
<?php
function safeRead(string $path): ?string {
// 抑制 warning,統一由函數返回 null 表示失敗
$content = @file_get_contents($path);
if ($content === false) {
$error = error_get_last();
error_log("Read failed: $path - {$error['message']}");
return null;
}
return $content;
}
// 或使用異常
function strictRead(string $path): string {
if (!is_file($path) || !is_readable($path)) {
throw new RuntimeException("File not readable: $path");
}
return file_get_contents($path);
}
總結:Filesystem 函數族是 PHP 處理檔案的基石。掌握高層 vs 低層**、**文字 vs 二進位**、**同步 vs 串流**、**鎖機制**、**串流封裝器**的選擇標準,能寫出高效、健壯、安全的檔案處理代碼。