透過 index.php?path=Base64編碼路徑 實現目錄瀏覽與檔案下載,支援虛擬掛載任意實體目錄(預設 F:)。
base64url_encode()/base64url_decode() 防止路徑注入..、./、雙斜線等危險模式Content-Disposition: attachment、支援 Accept-Ranges 斷點續傳$dir = "F:"; // 掛載根目錄
$path = "";
if (isset($_GET["path"])) {
$path = base64url_decode($_GET["path"]);
// 安全檢查
if (preg_match("#^[^/].*$|^.*\.$|^\..*$|\./\.|/\.|\./#", $path)) exit("非法路徑");
$path = preg_replace("#[/\/]{2,}#", "/", $path);
}
if (is_dir($dir . $path)) {
// 輸出目錄列表 HTML
$dh = opendir($dir . $path);
while ($filen = readdir($dh)) {
if ($filen == '.' || $filen == '..') continue;
$full = $dir . $path . '/' . $filen;
$enc = base64url_encode($path . '/' . $filen);
if (is_file($full)) {
echo "<a href='index.php?path=$enc'>$filen</a> (" . format_file_size(filesize($full)) . ")<br/>";
} else {
echo "<a href='index.php?path=$enc'>$filen</a><br/>";
}
}
// 父目錄連結
if ($path !== '') {
preg_match("#([^/]+/{1})*[^/]+(?=/)#", $path, $parent);
$parentPath = $parent ? '/'.$parent[0] : '/';
echo "<a href='index.php?path=" . base64url_encode($parentPath) . "'>..</a><br/>";
}
} elseif (is_file($dir . $path)) {
// 檔案下載
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Content-Length: " . filesize($dir.$path));
header("Content-Disposition: attachment; filename=" . basename($dir.$path));
readfile($dir.$path);
}
$dir 設為網站根目錄外的儲存區,避免洩露原始碼X-Sendfile 或 X-Accel-Redirect 交給 Web Server 處理