一個單文件 PHP 腳本,放入目錄即可通過 Web 瀏覽/下載該目錄下所有文件(排除自身),支援中文文件名、空格編碼、UTF-8/GBK 自動轉換。
<?php
// 配置區
$hide_files = ['index.php', '.git', '.htaccess', 'Thumbs.db']; // 隱藏文件
$encoding_detect = ['UTF-8', 'GBK', 'BIG5']; // 文件名編碼嘗試順序
// 掃描目錄
$files = [];
$dir = __DIR__;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
if (in_array($file, $hide_files, true)) continue;
if (is_dir($dir . '/' . $file)) continue; // 可選:遞歸顯示子目錄
$files[] = $file;
}
closedir($dh);
// 自然排序(數字感知)
natsort($files);
文件分享 - = htmlspecialchars(basename($dir)) ?>
📁 = htmlspecialchars(basename($dir)) ?>
目錄為空
0) {
$display_name = $try;
break;
}
}
?>
-
= htmlspecialchars($display_name) ?>
= format_size($size) ?>
= date('Y-m-d H:i', $mtime) ?>
= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}
opendir/readdir 比 scandir 記憶體友好(大目錄);natsort() 讓 file2.txt 排在 file10.txt 前;rawurlencode() (RFC 3986) 優於 urlencode(),空格編為 %20 而非 +;iconv 從 GBK/BIG5 轉 UTF-8,解決舊系統上傳文件名亂碼;htmlspecialchars() 防 XSS,rel="noopener" 防標籤劫持;if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_PW'] !== 'secret') { header('WWW-Authenticate: Basic realm="Private"'); header('HTTP/1.0 401 Unauthorized'); exit; };?dir=sub,需防目錄遍歷 realpath() 校驗;mime_content_type() 判斷;move_uploaded_file(),限制類型/大小;location /files/ { internal; alias /data/files/; } + PHP 簽名 URL(X-Accel-Redirect)。www-data 用戶);.env、config.php、.git 等加入 $hide_files;X-Sendfile/X-Accel-Redirect 交給 Web 服務器。 這個腳本適合臨時文件分享、內網資源發佈、靜態站點目錄索引,零配置即用。