萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 目錄遍歷完整教學:opendir、scandir、glob 與遞迴實作

PHP 應用開發中,目錄遍歷與檔案篩選是基本功。PHP 提供強大的目錄處理函式,掌握它們是開發者必備技能。

核心函式速查表

函式回傳型別用途
opendir()資源控制代碼開啟目錄取得控制代碼
is_dir()bool判斷是否為目錄
is_readable()bool判斷目錄是否可讀
readdir()string|false從控制代碼讀取單一檔名,指標後移
closedir()void關閉控制代碼釋放資源
scandir()array回傳目錄下所有檔案/目錄陣列
glob()array|false依模式比對檔案,支援萬用字元

基本遍歷:opendir + readdir

$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()

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>';
}

Flags 常用常數

常數說明
GLOB_MARK目錄名加斜線
GLOB_NOSORT不排序結果
GLOB_NOCHECK無比中傳回模式本身
GLOB_BRACE{a,b,c} 展開為多模式 (重要)
GLOB_ONLYDIR僅回傳目錄
GLOB_ERR讀取錯誤時停止 (預設忽略)

總結建議

  • 簡單列表:scandir() 最簡潔
  • 需篩選/模式比對:glob() 最強大
  • 需精細控制/舊版相容:opendir/readdir
  • 目錄樹結構:遞迴 + scandir
  • 記得永遠過濾 . .. 並檢查 is_readable
copyright © 萬盛學電腦網 all rights reserved