結合 PHP FTP 操作與 JS 動態摺疊,構建類檔案管理器的樹狀目錄瀏覽介面。
<script>
function initIt() {
var divs = document.all.tags("DIV");
for (var i=0; i
class="parent":可點擊展開/收合的目錄節點。class="child":預設隱藏的子目錄容器。plus.gif (展開)、open.gif (檔案/空目錄)、spacer.gif (縮進)。class Ftp {
var $conn, $host, $user, $pass, $pwd;
function init($host,$user,$pass) { /* ftp_connect + ftp_login */ }
function mulu() { return ftp_rawlist($this->conn, $this->pwd); } // 取得目錄列表
function initpwd($path) { $this->pwd=$path; }
function close() { ftp_quit($this->conn); }
}
function ftpurl($url, $depth, $isRoot, $name) {
global $HOST,$USER,$PASS;
if ($depth>10) return; // 防無限遞迴
$ftp = new Ftp(); $ftp->init($HOST,$USER,$PASS); $ftp->initpwd($url);
$list = $ftp->mulu(); $ftp->close();
$list = hsort($list); // 目錄優先排序
if (!$isRoot) echo '<div id="'.$name.'Child" class="child">';
foreach ($list as $item) {
$parts = explode(' ', $item);
$type = $parts[0][0]; // 'd' 目錄, '-' 檔案
$fname = end($parts);
if ($type=='d' && !in_array($fname, ['.','..'])) {
$v++; $newName = $isRoot ? "URL$v" : $name."_$v";
echo '<div id="'.$newName.'Parent" class="parent"><a href="#" onclick="expandIt(\''.$newName.'\')"><img src="img/plus.gif">'.$fname.'</a></div>';
ftpurl($url.'/'.$fname, $depth+1, 0, $newName);
} else {
echo '<a href="#"><img src="img/open.gif">'.$fname.'</a><br>';
}
}
if (!$isRoot) echo '</div>';
}
將 ftp_rawlist 回傳陣列按「目錄在前、檔案在後」重新排序。
img/plus.gif, open.gif, spacer.gif 圖示。此範例展示了 PHP 後端遞迴掃描與前端 JS 交互結合的經典模式。