首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

打造 AJAX + PHP 檔案管理系統:從列表、讀寫到刪除完整實作

     編輯:PHP 相關知識

系統功能架構

單頁面應用 (SPA) 風格,透過 AJAX 與後端 anfms.php 交互,實現檔案/目錄的列表、建立、讀取、寫入、刪除,介面採用模態彈窗操作。

前端核心模組 (ajax.js)

// 通用 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'); }

後端路由與處理 (anfms.php)

<?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() 驗證路徑在允許根目錄下。
  • 輸入過濾:檔名白名單、編碼轉換。
  • 權限控管:Session 驗證、角色區分。
  • CSRF Token:關鍵操作驗證 Token。
  • 錯誤訊息不外露系統路徑。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved