首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 掃描指定目錄並列出所有子目錄的方法

     編輯:PHP 綜合知識

前言

使用 scandir() 取得目錄條目,配合 is_dir() 過濾出子目錄,可構建簡易目錄瀏覽功能。

基本範例

<?php
echo "<h2>Subdirectories</h2><ul>";

$baseDir = dirname(__FILE__); // 當前腳本所在目錄
$targetDir = $baseDir . '/somedir/';

$entries = scandir($targetDir);
foreach ($entries as $item) {
    // 跳過 . 與 ..
    if ($item === '.' || $item === '..') continue;

    $fullPath = $targetDir . $item;
    if (is_dir($fullPath)) {
        echo "<li><a href='?subdir=$item'>$item</a></li>";
    }
}
echo "</ul>";
?>

進階:遞迴列出所有層級子目錄

function listDirsRecursive($dir, $level = 0) {
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $path = $dir . '/' . $item;
        if (is_dir($path)) {
            echo str_repeat('  ', $level) . "- $item\n";
            listDirsRecursive($path, $level + 1);
        }
    }
}

listDirsRecursive('/path/to/root');

效能提示

  • scandir() 會一次讀取所有條目到記憶體,超大目錄(萬檔以上)建議改用 opendir() + readdir() 迭代器模式。
  • 生產環境應加入權限檢查(is_readable())、例外處理與快取機制。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved