利用 opendir/readdir、chdir、getcwd 等目錄函數,結合 GET 參數 Base64 編碼傳遞絕對路徑,實現簡易的 Web 目錄瀏覽與進入功能。
<?php
if (isset($_GET['id'])) {
$s = str_replace(' ', '+', $_GET['id']);
$s = base64_decode($s);
chdir($s);
}
$a = opendir('.');
while (false !== ($c = readdir($a))) {
if (is_dir($c)) {
if ($c === '.') {
continue;
} elseif ($c === '..') {
$parent = substr(getcwd(), 0, strrpos(getcwd(), '\\'));
$w = base64_encode($parent);
echo "上一級 <a href='?id=$w'>打開</a><br/>";
} else {
$w = base64_encode(getcwd() . '\\' . $c);
echo "$c <a href='?id=$w'>打開</a><br/>";
}
} else {
echo "$c 不是目錄<br/>";
}
}
?>
| 函數 | 用途 |
|---|---|
opendir() | 打開目錄句柄 |
readdir() | 讀取目錄條目(含 . 和 ..) |
is_dir() | 判斷是否為目錄 |
chdir() | 改變當前工作目錄 |
getcwd() | 獲取當前工作目錄絕對路徑 |
base64_encode/decode | 路徑安全傳遞(含特殊字符) |
realpath() + 前綴匹配),防止 ../../etc/passwd 攻擊。\\、中文文件名編碼轉換(iconv/mb_convert_encoding)。RecursiveDirectoryIterator (SPL) 或 glob(),代碼更健壯簡潔。htmlspecialchars() 防 XSS。$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
echo $file->getPathname() . '<br/>';
}