萬盛學電腦網

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

PHP 無限層級目錄遞迴遍歷實作:目錄樹瀏覽器範例

核心函數對照

函數用途
opendir()開啟目錄控制代碼
readdir()讀取目錄下一項(檔案或子目錄)
is_dir()判斷路徑是否為目錄
chdir()切換當前工作目錄
getcwd()取得當前工作目錄絕對路徑
closedir()關閉目錄控制代碼

簡易版:單層遞迴瀏覽(含超連結導航)

<?php
// 6.php - 目錄瀏覽器
if (isset($_GET['id'])) {
    $target = $_GET['id'];
    // 安全性:限制在允許的根目錄下
    $basePath = realpath('/var/www/html');
    $realTarget = realpath($target);
    if ($realTarget && strpos($realTarget, $basePath) === 0) {
        chdir($realTarget);
    }
}

echo '當前目錄:' . getcwd() . '<br>';

$handle = opendir('.');
while (($entry = readdir($handle)) !== false) {
    if ($entry === '.' || $entry === '..') continue;
    
    $fullPath = getcwd() . DIRECTORY_SEPARATOR . $entry;
    
    if (is_dir($fullPath)) {
        // 目錄:顯示連結可進入
        $url = urlencode($fullPath);
        echo "📁 $entry <a href='6.php?id=$url'>[進入]</a><br>";
    } else {
        // 檔案:直接顯示
        echo "📄 $entry<br>";
    }
}
closedir($handle);
?>

進階版:樹狀結構輸出(HTML 巢狀清單)

<?php
function renderDirTree($path, $baseUrl = '', $depth = 0) {
    if ($depth > 10) return; // 防無限遞迴
    if (!is_dir($path)) return;
    
    $handle = opendir($path);
    $entries = [];
    
    while (($entry = readdir($handle)) !== false) {
        if ($entry !== '.' && $entry !== '..') {
            $entries[] = $entry;
        }
    }
    closedir($handle);
    
    // 目錄優先、字母排序
    usort($entries, function($a, $b) use ($path) {
        $aDir = is_dir($path . DIRECTORY_SEPARATOR . $a);
        $bDir = is_dir($path . DIRECTORY_SEPARATOR . $b);
        if ($aDir !== $bDir) return $aDir ? -1 : 1;
        return strnatcasecmp($a, $b);
    });
    
    echo str_repeat('  ', $depth) . "<ul>\n";
    foreach ($entries as $entry) {
        $fullPath = $path . DIRECTORY_SEPARATOR . $entry;
        $isDir = is_dir($fullPath);
        $icon = $isDir ? '📁' : '📄';
        $link = $isDir ? "<a href='?dir=" . urlencode($fullPath) . "'>$entry</a>" : $entry;
        echo str_repeat('  ', $depth + 1) . "<li>$icon $link</li>\n";
        if ($isDir) {
            renderDirTree($fullPath, $baseUrl, $depth + 1);
        }
    }
    echo str_repeat('  ', $depth) . "</ul>\n";
}

// 使用
$root = isset($_GET['dir']) ? urldecode($_GET['dir']) : __DIR__;
// 安全性檢查...
renderDirTree($root);
?>

SPL 現代化寫法(PHP 5.3+,推薦)

<?php
function scanDirRecursive($path) {
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $fileInfo) {
        $depth = $iterator->getDepth();
        $indent = str_repeat('  ', $depth);
        $prefix = $fileInfo->isDir() ? '📁 ' : '📄 ';
        echo "$indent$prefix{$fileInfo->getFilename()}<br>\n";
    }
}

scanDirRecursive('/var/www/html');
?>

安全性重點(生產環境必須)

  1. 路徑限制:使用 realpath() 確保目標路徑在允許根目錄下,防止目錄遍歷攻擊(../../etc/passwd)。
  2. 權限檢查:is_readable() 確認可讀後再操作。
  3. 輸出編碼:檔名輸出 HTML 時使用 htmlspecialchars() 防 XSS。
  4. 資源釋放:確保 closedir() 或迭代器正確銷毀。

效能優化建議

  • 大目錄使用 RecursiveDirectoryIterator 而非遞迴函數(避免呼叫堆疊溢位)。
  • 快取目錄結構(如 Redis、檔案快取),避免重複掃描。
  • 分頁/懶加載:前端配合 JS 動態載入子目錄。
copyright © 萬盛學電腦網 all rights reserved