萬盛學電腦網

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

PHP 列出當前目錄所有子目錄並生成導航索引

需求場景

本地開發環境 (XAMPP) 多專案共存,根目錄不想放雜項,需要一個自動生成的專案索引頁,新增專案自動顯示,無需手動維護靜態 HTML。

核心實作

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>專案索引</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
        h1 { color: #333; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
        .projects { list-style: none; padding: 0; }
        .projects li { margin: 0.5rem 0; }
        .projects a { display: block; padding: 0.75rem 1rem; background: #f8f9fa; border-radius: 4px; color: #0366d6; text-decoration: none; transition: background 0.2s; }
        .projects a:hover { background: #e1ecf4; text-decoration: underline; }
        .meta { font-size: 0.85rem; color: #666; margin-left: 1rem; }
    </style>
</head>
<body>
    <h1>📁 本地專案索引</h1>
    <ul class="projects">
<?php
$dir = __DIR__; // 當前腳本目錄
$items = scandir($dir);

foreach ($items as $item) {
    // 跳過隱藏檔、當前/上層目錄、非目錄、腳本自身
    if ($item === '.' || $item === '..' || $item === basename(__FILE__)) continue;
    $path = $dir . DIRECTORY_SEPARATOR . $item;
    if (!is_dir($path)) continue;

    // 可選:讀取專案描述 (README.md 首行、composer.json name 等)
    $desc = '';
    if (is_file($path . '/README.md')) {
        $firstLine = trim(explode("\n", file_get_contents($path . '/README.md'))[0] ?? '');
        $desc = $firstLine ? " — $firstLine" : '';
    }

    // 輸出連結 (相對路徑)
    $href = rawurlencode($item) . '/';
    echo "        
  • $item$desc
  • \n"; } ?> </ul> </body> </html>

    進階增強功能

    1. 遞歸顯示目錄樹 (可摺疊)

    <?php
    function renderTree($path, $depth = 0, $maxDepth = 3)
    {
        if ($depth > $maxDepth) return;
        $items = scandir($path);
        echo "
      \n"; foreach ($items as $item) { if ($item === '.' || $item === '..') continue; $full = $path . DIRECTORY_SEPARATOR . $item; if (is_dir($full)) { echo "
    • 📁 $item"; renderTree($full, $depth + 1, $maxDepth); echo "
    • \n"; } else { echo "
    • 📄 $item
    • \n"; } } echo "
    \n"; } renderTree(__DIR__);

    2. 顯示專案狀態 (Git 分支、Composer 依賴、最後修改時間)

    <?php
    function getProjectMeta($path)
    {
        $meta = [];
        // Git 分支
        if (is_dir($path . '/.git')) {
            $head = @file_get_contents($path . '/.git/HEAD');
            if ($head && preg_match('/ref: refs\/heads\/(.+)/', $head, $m)) {
                $meta['branch'] = trim($m[1]);
            }
        }
        // Composer 專案名
        if (is_file($path . '/composer.json')) {
            $composer = json_decode(file_get_contents($path . '/composer.json'), true);
            $meta['name'] = $composer['name'] ?? '';
        }
        // 最後修改
        $meta['mtime'] = date('Y-m-d H:i', filemtime($path));
        return $meta;
    }

    3. 搜尋/過濾功能 (前端 JS 即時過濾)

    <input type="search" id="filter" placeholder="輸入專案名過濾..." style="width:100%;padding:0.5rem;margin-bottom:1rem">
    <script>
    document.getElementById('filter').addEventListener('input', e => {
        const q = e.target.value.toLowerCase();
        document.querySelectorAll('.projects li').forEach(li => {
            li.style.display = li.textContent.toLowerCase().includes(q) ? '' : 'none';
        });
    });
    </script>

    部署建議

    • 將此檔案命名為 index.php 放置於站點根目錄 (如 htdocs/)。
    • 配合 Apache DirectoryIndex index.php,訪問 https://localhost/ 即可看到索引。
    • 新增專案只需在根目錄建立資料夾,自動出現於列表。
    • 生產環境請加入身份驗證或 IP 白名單,避免洩露目錄結構。

    這個小工具體現「程序員懶惰美德」:一次編寫,長期受益,避免重複手工維護導航頁。

    copyright © 萬盛學電腦網 all rights reserved