前言
檔案系統操作是後端開發的基本功。本文系統整理 PHP 檔案/目錄核心函數:路徑解析、讀寫模式、指標控制、目錄遍歷、屬性獲取、權限管理、原子操作與安全防範。
一、路徑解析與資訊獲取
| 函數 | 功能 | 範例 |
| basename($path, $suffix?) | 取得檔名 | basename('/path/file.txt') → 'file.txt' |
| dirname($path) | 取得目錄路徑 | dirname('/path/file.txt') → '/path' |
| pathinfo($path, $options?) | 解析路徑資訊 | ['dirname'=>'/path', 'basename'=>'file.txt', 'extension'=>'txt', 'filename'=>'file'] |
| realpath($path) | 解析絕對路徑 (解析符號連結、..、.) | realpath('../file') → '/absolute/path/file' |
| is_file($path) | 是否為一般檔案 | |
| is_dir($path) | 是否為目錄 | |
| file_exists($path) | 檔案或目錄存在 | |
二、檔案讀取操作
1. 一次性讀取 (小檔案)
// 字串
$content = file_get_contents('data.txt');
// 陣列 (每行一元素,含換行符)
$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2. 串流讀取 (大檔案、記憶體友善)
$fp = fopen('large.log', 'r');
while (($line = fgets($fp)) !== false) {
// 處理單行
if (str_contains($line, 'ERROR')) {
error_log($line);
}
}
fclose($fp);
// CSV 解析
$fp = fopen('data.csv', 'r');
while (($row = fgetcsv($fp)) !== false) {
// $row 為陣列
}
fclose($fp);
3. 二進制讀取與指標控制
$fp = fopen('binary.dat', 'rb');
fseek($fp, 1024, SEEK_SET); // 移至位移 1024
fseek($fp, -64, SEEK_END); // 從尾部倒退 64 位元組
$data = fread($fp, 256); // 讀 256 位元組
$pos = ftell($fp); // 目前指標位置
rewind($fp); // 回到開頭
fclose($fp);
4. 解析 .ini 設定檔
$config = parse_ini_file('config.ini', true); // true 解析 section
// config.ini:
// [database]
// host = "localhost"
// port = 3306
// 結果: ['database' => ['host'=>'localhost', 'port'=>3306]]
三、檔案寫入操作
1. 一次性寫入
file_put_contents('data.txt', $content); // 覆蓋
file_put_contents('data.txt', $content, FILE_APPEND); // 追加
file_put_contents('data.txt', $content, LOCK_EX); // 獨佔鎖寫入 (原子)
2. 串流寫入 (大檔案、併發安全)
$fp = fopen('data.txt', 'c+'); // 讀寫,不截斷,不存在則建立
if (flock($fp, LOCK_EX)) { // 獨佔鎖 (阻塞)
ftruncate($fp, 0); // 清空內容
fwrite($fp, $newContent);
fflush($fp); // 強制刷新到磁碟
flock($fp, LOCK_UN); // 釋放鎖
}
fclose($fp);
3. 原子寫入模式 (避免部分寫入被讀取)
$tmpName = tempnam(sys_get_temp_dir(), 'atomic_');
file_put_contents($tmpName, $content);
rename($tmpName, $targetFile); // rename 在同檔案系統是原子操作
四、目錄操作
1. 遍歷目錄 (三種方式)
// 1. DirectoryIterator (OO、SPL、記憶體效率佳)
$dir = new DirectoryIterator('/path/to/dir');
foreach ($dir as $fileInfo) {
if ($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . ' ' . $fileInfo->getSize() . ' ' . $fileInfo->getMTime() . "\n";
}
// 2. RecursiveDirectoryIterator (遞迴)
$rdi = new RecursiveDirectoryIterator('/path');
$rii = new RecursiveIteratorIterator($rdi);
foreach ($rii as $file) {
if ($file->isFile()) echo $file->getPathname() . "\n";
}
// 3. glob (模式匹配)
$files = glob('/path/*.php'); // 返回絕對路徑陣列
$files = glob('/path/*', GLOB_ONLYDIR); // 僅目錄
// 4. scandir (傳統、返回陣列、含 . 和 ..)
$entries = scandir('/path');
2. 建立/刪除目錄
mkdir('/path/to/dir', 0755, true); // true 遞迴建立
rmdir('/path/to/empty_dir'); // 僅能刪除空目錄
// 遞迴刪除目錄樹
function rrmdir(string $dir): void {
$files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
$path = "$dir/$file";
is_dir($path) ? rrmdir($path) : unlink($path);
}
rmdir($dir);
}
五、檔案屬性與權限
| 函數 | 功能 | 範例 |
| filemtime($file) | 最後修改時間 (Unix timestamp) | date('Y-m-d H:i:s', filemtime($file)) |
| fileatime($file) | 最後存取時間 | |
| filectime($file) | inode 變更時間 (權限、擁有者、連結數) | |
| filesize($file) | 檔案大小 (位元組) | |
| fileperms($file) | 權限位元遮罩 | substr(sprintf('%o', fileperms($file)), -4) → '0644' |
| fileowner($file) | 擁有者 UID | posix_getpwuid(fileowner($file))['name'] |
| filegroup($file) | 群組 GID | posix_getgrgid(filegroup($file))['name'] |
| filetype($file) | 類型 | file, dir, link, char, block, fifo, socket |
| stat($file) | 完整屬性陣列 (同 C stat struct) | ['dev'=>..., 'ino'=>..., 'mode'=>..., 'uid'=>..., 'size'=>..., 'atime'=>..., 'mtime'=>..., 'ctime'=>...] |
權限修改
chmod($file, 0644); // 檔案權限
chown($file, 'www-data'); // 擁有者 (需 root)
chgrp($file, 'www-data'); // 群組
六、檔案上傳處理 ($_FILES)
// 表單需 enctype="multipart/form-data"
if (isset($_FILES['avatar'])) {
$file = $_FILES['avatar'];
// 錯誤檢查
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('上傳錯誤: ' . $file['error']);
}
// 安全驗證
$allowedMimes = ['image/jpeg', 'image/png', 'image/webp'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
if (!in_array($mime, $allowedMimes)) {
throw new Exception('檔案類型不允許');
}
// 產生安全檔名
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$newName = bin2hex(random_bytes(16)) . '.' . $ext;
$dest = "/var/www/uploads/$newName";
// 移動 (跨檔案系統安全)
if (!move_uploaded_file($file['tmp_name'], $dest)) {
throw new Exception('移動檔案失敗');
}
// 設定權限
chmod($dest, 0644);
}
七、安全最佳實務
- 路徑遍歷防護:
realpath($userInput) 確保在允許目錄內
- 檔名安全化:不信任用戶檔名,使用隨機名 + 驗證副檔名/MIME
- 上傳目錄執行權限移除:Nginx/Apache 設定
location /uploads { php_flag engine off; }
- 大小限制:php.ini
upload_max_filesize, post_max_size + 程式碼二次檢查
- 暫存檔清理:上傳失敗/異常時確保
$_FILES['tmp_name'] 被清理 (PHP 會自動清理請求結束的暫存檔)
總結
檔案操作核心原則:小檔案用 file_get_contents/put_contents,大檔案用串流 fopen/fread/fwrite,併發寫入必加 flock/原子重命名,路徑必經 realpath 正規化,上傳必驗證 MIME 與隨機化檔名。善用 SPL 迭代器 (DirectoryIterator, GlobIterator) 替代傳統 scandir/glob,獲得更好的記憶體效能與物件導向介面。
copyright ©
萬盛學電腦網 all rights reserved