You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP+AJAX实现无页面加载的目录文件列表?

Hey there! Let's break down how to build this no-page-refresh file storage and directory listing feature with PHP and AJAX, no database needed—perfect call there.

核心实现逻辑

This feature relies on two main parts: front-end AJAX/Fetch calls to communicate with the server without reloading, and back-end PHP scripts to handle file system operations.

1. Front-End (AJAX/Fetch)

Directory Listing Flow

  • When the page loads, use JavaScript to send a GET request to a PHP endpoint (e.g., get_files.php).
  • Once the server returns a JSON array of files/directories, dynamically render this list into your HTML (vanilla JS works great here—no heavy libraries required).
  • Add a manual refresh button or auto-refresh logic if you want the list to update without user input.

File Upload Flow

  • Create an HTML form with a file input, but override the default form submission behavior with JavaScript.
  • Use the FormData object to wrap the file input data, then send a POST request to a PHP upload endpoint (e.g., upload_file.php).
  • Handle the server's success/error response and update the UI immediately (like adding the new file to the list without reloading the page).

Example snippets to illustrate:

// Fetch and render directory list
async function loadFileList() {
  try {
    const response = await fetch('get_files.php');
    const files = await response.json();
    const listContainer = document.getElementById('file-list');
    listContainer.innerHTML = ''; // Clear existing list

    files.forEach(file => {
      const listItem = document.createElement('div');
      listItem.textContent = `${file.name}${file.is_dir ? ' (Directory)' : ''}`;
      listContainer.appendChild(listItem);
    });
  } catch (error) {
    console.error('Failed to load files:', error);
  }
}

// Handle file upload
document.getElementById('upload-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  const formData = new FormData(e.target);
  
  try {
    const response = await fetch('upload_file.php', {
      method: 'POST',
      body: formData
    });
    const result = await response.json();

    if (result.success) {
      alert('File uploaded successfully!');
      loadFileList(); // Refresh the list right away
    } else {
      alert(`Upload failed: ${result.message}`);
    }
  } catch (error) {
    console.error('Upload error:', error);
  }
});

2. Back-End (PHP)

Directory Listing Endpoint (get_files.php)

  • Define your target directory (e.g., ./uploads/).
  • Use PHP's file system functions like scandir() or glob() to read directory contents.
  • Filter out the default . and .. entries, then collect details like file name, size, and whether it's a directory.
  • Convert the array to JSON and send it back with the correct Content-Type header.

Example code:

<?php
header('Content-Type: application/json');

$targetDir = './uploads/';
// Create directory if it doesn't exist
if (!is_dir($targetDir)) {
    mkdir($targetDir, 0755, true);
}

$files = [];
$dirContents = scandir($targetDir);

foreach ($dirContents as $item) {
    if ($item === '.' || $item === '..') continue;
    $itemPath = $targetDir . $item;
    $files[] = [
        'name' => $item,
        'is_dir' => is_dir($itemPath),
        'size' => filesize($itemPath)
    ];
}

echo json_encode($files);
?>

File Upload Endpoint (upload_file.php)

  • Check if the file was uploaded correctly using $_FILES.
  • Validate the file: check for upload errors, limit file size, restrict allowed file types (to block malicious uploads like PHP scripts).
  • Move the temporary file to your target directory using move_uploaded_file().
  • Return a JSON response indicating success or failure.

Example code:

<?php
header('Content-Type: application/json');

$targetDir = './uploads/';
$allowedTypes = ['image/jpeg', 'image/png', 'text/plain', 'application/pdf'];
$maxSize = 5 * 1024 * 1024; // 5MB limit

if (!isset($_FILES['file'])) {
    echo json_encode(['success' => false, 'message' => 'No file uploaded']);
    exit;
}

$file = $_FILES['file'];

// Check for upload errors
if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'Upload error: ' . $file['error']]);
    exit;
}

// Validate file type and size
if (!in_array($file['type'], $allowedTypes)) {
    echo json_encode(['success' => false, 'message' => 'File type not allowed']);
    exit;
}

if ($file['size'] > $maxSize) {
    echo json_encode(['success' => false, 'message' => 'File too large (max 5MB)']);
    exit;
}

// Generate a safe, unique filename to avoid overwrites
$fileName = uniqid() . '_' . basename($file['name']);
$targetPath = $targetDir . $fileName;

// Move the uploaded file to the target directory
if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    echo json_encode(['success' => true, 'message' => 'File uploaded']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save file']);
}
?>
Key Security Notes
  • Prevent path traversal: Never let users specify arbitrary directories (if you need subdirectory support, sanitize input heavily).
  • Restrict file types: Always validate MIME types and extensions to block executable files like .php or .exe.
  • Set secure permissions: Ensure your upload directory has permissions like 0755 (directories) and 0644 (files) to prevent script execution.
  • Sanitize filenames: Use uniqid() or similar to avoid overwriting existing files and block malicious characters.
  • PHP Official Documentation: The most authoritative source for file system functions (like scandir, move_uploaded_file) and JSON handling.
  • MDN Web Docs: Their guides on Fetch API, FormData, and AJAX are perfect for mastering front-end server communication.
  • PHP-focused tech blogs: Many free tutorials cover exactly this file system + AJAX workflow, with step-by-step examples and troubleshooting tips.

内容的提问来源于stack exchange,提问作者user8718268

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:38:05