本地開發環境 (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 ? " " : '';
}
// 輸出連結 (相對路徑)
$href = rawurlencode($item) . '/';
echo " $item$desc \n";
}
?>
</ul>
</body>
</html>
<?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__);
<?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;
}
<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/)。DirectoryIndex index.php,訪問 https://localhost/ 即可看到索引。這個小工具體現「程序員懶惰美德」:一次編寫,長期受益,避免重複手工維護導航頁。