PHP 應用開發中,目錄遍歷與檔案篩選是基本功。PHP 提供強大的目錄處理函式,掌握它們是開發者必備技能。
| 函式 | 回傳型別 | 用途 |
|---|---|---|
| opendir() | 資源控制代碼 | 開啟目錄取得控制代碼 |
| is_dir() | bool | 判斷是否為目錄 |
| is_readable() | bool | 判斷目錄是否可讀 |
| readdir() | string|false | 從控制代碼讀取單一檔名,指標後移 |
| closedir() | void | 關閉控制代碼釋放資源 |
| scandir() | array | 回傳目錄下所有檔案/目錄陣列 |
| glob() | array|false | 依模式比對檔案,支援萬用字元 |
$dir = './mypics';
if (is_dir($dir) && is_readable($dir)) {
$handle = opendir($dir);
while (($file = readdir($handle)) !== false) {
if ($file !== '.' && $file !== '..') {
echo $file . '<br>';
}
}
closedir($handle);
}
readdir 回傳 false 表示結束。需過濾 . (目前目錄) 與 .. (上層目錄)。
function getFilesByExt($dir, $extensions = []) {
$result = [];
if (!is_dir($dir) || !is_readable($dir)) return $result;
$handle = opendir($dir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . '/' . $file;
if (is_dir($path)) continue; // 僅檔案
if (empty($extensions)) {
$result[] = $file;
} else {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $extensions)) $result[] = $file;
}
}
closedir($handle);
return $result;
}
// 使用:取得 mypics 下所有 jpeg、png
$images = getFilesByExt('./mypics', ['jpeg', 'png', 'jpg', 'gif']);
function scanDirRecursive($dir) {
$result = ['dirs' => [], 'files' => []];
if (!is_dir($dir) || !is_readable($dir)) return $result;
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$path = $dir . '/' . $item;
if (is_dir($path)) {
$result['dirs'][$item] = scanDirRecursive($path);
} else {
$result['files'][] = $item;
}
}
return $result;
}
$tree = scanDirRecursive('./mypics');
print_r($tree);
使用 scandir 簡化程式碼,遞迴建構巢狀陣列結構。
glob(string $pattern, int $flags = 0):$pattern 為類 Shell 萬用字元模式,非單純目錄字串。
// 列出 d:/wamp 所有檔案
foreach (glob("d:/wamp/*") as $file) echo $file . '<br>';
// 列出所有 bmp
foreach (glob("d:/wamp/*.bmp") as $file) echo $file . '<br>';
// 多副檔名 (需 GLOB_BRACE)
foreach (glob("d:/wamp/{*.jpeg,*.jpg,*.gif}", GLOB_BRACE) as $file) echo $file . '<br>';
// 目錄結構:wallpaper/分類/thumb/*.jpg
foreach (glob("wallpaper/*/thumb/*") as $file) {
echo $file . '<br>';
}
| 常數 | 說明 |
|---|---|
| GLOB_MARK | 目錄名加斜線 |
| GLOB_NOSORT | 不排序結果 |
| GLOB_NOCHECK | 無比中傳回模式本身 |
| GLOB_BRACE | {a,b,c} 展開為多模式 (重要) |
| GLOB_ONLYDIR | 僅回傳目錄 |
| GLOB_ERR | 讀取錯誤時停止 (預設忽略) |
scandir() 最簡潔glob() 最強大opendir/readdirscandir. .. 並檢查 is_readable