單頁面應用 (SPA) 風格,透過 AJAX 與後端 anfms.php 交互,實現檔案/目錄的列表、建立、讀取、寫入、刪除,介面採用模態彈窗操作。
// 通用 AJAX 請求封裝
function ajaxRequest(action, params, targetId) {
const xhr = new XMLHttpRequest();
const url = `anfms.php?action=${action}&${params}`;
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
document.getElementById(targetId).innerHTML = xhr.responseText;
}
};
xhr.open('GET', url, true);
xhr.setRequestHeader('If-Modified-Since', '0');
xhr.send();
}
// 具體功能調用
function file_list(path) { ajaxRequest('filelist', 'path=' + encodeURIComponent(path), 'file_list'); }
function file_delete(file) { if (confirm('確認刪除?')) ajaxRequest('delete_file', 'file=' + encodeURIComponent(file), 'file_list'); }
function file_content_input(data) { ajaxRequest('inputcontent', data, 'file_content_input'); }
<?php
header('Content-Type: text/html; charset=utf-8');
$root = $_SERVER['DOCUMENT_ROOT'];
$action = $_GET['action'] ?? '';
switch ($action) {
case 'filelist':
$path = $root . $_GET['path'];
$dir = opendir($path);
echo '<div class="file_list_t">';
while (($file = readdir($dir)) !== false) {
if ($file === '..') continue;
$full = $path . '/' . $file;
$isDir = is_dir($full);
$icon = $isDir ? '📁' : '📄';
$size = $isDir ? '' : ' - ' . round(filesize($full)/1024, 1) . 'KB';
$del = $isDir ? "dir_delete('$full')" : "file_delete('$full')";
echo "<li>$icon $file$size <span><a href='#' onclick=\"if(confirm('確認?')) $del\">刪除</a></span></li>";
}
echo '</div>';
break;
case 'inputcontent':
$fp = fopen($root . '/' . $_GET['input_name'], 'ab');
fwrite($fp, "data:" . date('Y-m-d H:i:s') . " content:" . $_GET['input_content'] . "\n");
fclose($fp);
echo '成功寫入';
break;
// ... getcontent, filemake, delete_dir 等
}
realpath() 驗證路徑在允許根目錄下。