類似 Apache mod_autoindex 或 Nginx autoindex on,本腳本單一檔案即可實現目錄瀏覽、檔案下載、原始碼高亮顯示。
<?php
// directory_index.php
error_reporting(E_ALL & ~E_NOTICE);
// 取得請求路徑,預設為當前目錄
$requestPath = isset($_GET['dir']) ? $_GET['dir'] : '.';
$realPath = realpath($requestPath);
if (!$realPath || !is_readable($realPath)) {
http_response_code(404);
die('目錄不存在或不可讀');
}
// 安全性:限制在指定根目錄下(防止目錄遍歷)
$rootBase = realpath(__DIR__ . '/public'); // 設定您的公開根目錄
if (strpos($realPath, $rootBase) !== 0) {
http_response_code(403);
die('存取被拒絕:路徑超出允許範圍');
}
// 若為檔案:顯示原始碼或直接下載
if (is_file($realPath)) {
$ext = strtolower(pathinfo($realPath, PATHINFO_EXTENSION));
$highlightExts = ['php', 'php5', 'phtml', 'inc', 'js', 'css', 'html', 'htm', 'sql', 'xml', 'json', 'md', 'txt', 'py', 'sh', 'c', 'cpp', 'h', 'java'];
if (in_array($ext, $highlightExts)) {
header('Content-Type: text/plain; charset=UTF-8');
highlight_file($realPath);
} else {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($realPath) . '"');
header('Content-Length: ' . filesize($realPath));
readfile($realPath);
}
exit;
}
// 目錄列表
$iterator = new FilesystemIterator($realPath, FilesystemIterator::SKIP_DOTS | FilesystemIterator::KEY_AS_PATHNAME);
$items = [];
foreach ($iterator as $path => $file) {
$items[] = [
'name' => $file->getFilename() . ($file->isDir() ? '/' : ''),
'path' => $path,
'is_dir' => $file->isDir(),
'size' => $file->isFile() ? $file->getSize() : null,
'mtime' => $file->getMTime(),
];
}
// 排序:目錄優先,再按名稱
usort($items, function($a, $b) {
if ($a['is_dir'] !== $b['is_dir']) return $b['is_dir'] ? 1 : -1;
return strnatcasecmp($a['name'], $b['name']);
});
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>目錄索引: <?= htmlspecialchars($realPath) ?></title>
<style>
body { font-family: monospace; margin: 2rem; }
table { border-collapse: collapse; width: 100%; }
th, td { padding: 0.5rem; text-align: left; border-bottom: 1px solid #eee; }
th { background: #f5f5f5; }
a { text-decoration: none; color: #0366d6; }
a:hover { text-decoration: underline; }
.dir { font-weight: bold; color: #22863a; }
.size { text-align: right; color: #666; }
.time { color: #666; white-space: nowrap; }
.parent { margin-bottom: 1rem; }
</style>
</head>
<body>
<h1>目錄索引: <?= htmlspecialchars($realPath) ?></h1>
<div class="parent">
<a href="?dir== urlencode(dirname($realPath)) ?>>.. (上層目錄)</a>
</div>
<table>
<thead>
<tr><th>名稱</th><th class="size">大小</th><th class="time">修改時間</th></tr>
</thead>
<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td>
<a href="?dir== urlencode($item['path']) ?>" class="= $item['is_dir'] ? 'dir' : '' ?>">
<?= htmlspecialchars($item['name']) ?>
</a>
</td>
<td class="size"><?= $item['size'] !== null ? human_readable($item['size']) : '-' ?></td>
<td class="time"><?= date('Y-m-d H:i', $item['mtime']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
<?php
function human_readable($bytes) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units)-1) {
$bytes /= 1024; $i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}
?>
public/index.php)$rootBase 為您允許瀏覽的根目錄絕對路徑location /files/ {
alias /var/www/files/;
try_files $uri $uri/ /directory_index.php?dir=$document_uri;
}
highlight_file 或限制副檔名,避免洩露敏感程式碼robots.txt 禁止搜尋引擎索引單一檔案即可實現功能完整的目錄索引,支援原始碼高亮、人類可讀檔案大小、時間排序,適合開發環境、檔案分享站快速部署。