利用 opendir、readdir、chdir、getcwd 等檔案系統函數,結合遞迴邏輯即可實現目錄樹狀瀏覽。以下示範一個可點擊展開子目錄的簡易檔案管理器雛形。
isset():檢查 $_GET['id'] 是否存在base64_decode():解碼傳遞的目錄絕對路徑chdir():切換工作目錄至指定路徑opendir('.'):開啟當前目錄readdir():循環讀取目錄項目is_dir():判斷是目錄還是檔案getcwd():取得當前工作目錄絕對路徑base64_encode():編碼路徑供 URL 傳遞<?php
if (isset($_GET['id'])) {
$path = base64_decode(str_replace(' ', '+', $_GET['id']));
chdir($path);
}
$handle = opendir('.');
while (false !== ($entry = readdir($handle))) {
if (is_dir($entry)) {
if ($entry === '.') {
continue;
} elseif ($entry === '..') {
$parent = base64_encode(substr(getcwd(), 0, strrpos(getcwd(), DIRECTORY_SEPARATOR)));
echo "上一級 <a href='?id=$parent'>打開</a><br />";
} else {
$full = base64_encode(getcwd() . DIRECTORY_SEPARATOR . $entry);
echo "$entry <a href='?id=$full'>打開</a><br />";
}
} else {
echo "$entry 不是目錄<br />";
}
}
closedir($handle);
?>
id 參數傳遞chdir 切換至該目錄,再次列出內容.. 連結透過 strrpos 計算父目錄路徑注意:實際部署請加入路徑安全檢查(防止目錄遍歷攻擊),並建議改用 RecursiveDirectoryIterator 等 SPL 類別獲得更穩健的實作。