萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 打造 Web 檔案管理系統:目錄列表、上傳、下載、刪除完整實作

PHP 打造 Web 檔案管理系統:目錄列表、上傳、下載、刪除完整實作

利用 PHP 豐富的檔案系統函數 (opendir, readdir, copy, unlink, mkdir 等) 可快速建立瀏覽器端的檔案管理器。本文提供完整、安全、現代化的實作範例,包含路徑安全防護、MIME 偵測、分頁、AJAX 上傳。

核心安全原則

⚠️ 路徑遍歷攻擊防護 (Path Traversal) 是檔案管理系統的第一大風險
  • 永遠使用 realpath() 解析絕對路徑
  • 嚴格檢查解析後路徑是否在允許的根目錄下 (str_starts_with($realPath, $rootRealPath))
  • 禁止直接信任用戶輸入的相對路徑 (../, 符號連結)
  • 檔名白名單驗證、副檔名與 MIME 雙重檢查

完整單檔版檔案管理器 (PHP 8.1+)

<?php
declare(strict_types=1);

const ROOT_DIR = __DIR__ . '/storage'; // 僅允許存取此目錄下
const MAX_UPLOAD_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_MIMES = [
    'image/jpeg', 'image/png', 'image/gif', 'image/webp',
    'application/pdf', 'text/plain', 'text/csv',
    'application/zip', 'application/x-zip-compressed',
];

// 確保根目錄存在
if (!is_dir(ROOT_DIR)) mkdir(ROOT_DIR, 0755, true);

// 路徑安全解析
function resolvePath(string $relPath): string|false {
    $relPath = ltrim($relPath, '/\\');
    $target = realpath(ROOT_DIR . DIRECTORY_SEPARATOR . $relPath);
    $rootReal = realpath(ROOT_DIR);
    if ($target === false || !str_starts_with($target, $rootReal)) {
        return false; // 跳出根目錄
    }
    return $target;
}

// 處理動作
$action = $_GET['action'] ?? 'list';
$path = $_GET['path'] ?? '';
$realPath = resolvePath($path);
if ($realPath === false) { http_response_code(400); die('非法路徑'); }

switch ($action) {
    case 'list':
        listDirectory($realPath, $path);
        break;
    case 'download':
        downloadFile($realPath);
        break;
    case 'delete':
        deleteFile($realPath);
        break;
    case 'upload':
        uploadFile($realPath);
        break;
    case 'mkdir':
        makeDirectory($realPath);
        break;
    default:
        http_response_code(404);
        echo '未知操作';
}

function listDirectory(string $realPath, string $relPath): void {
    $items = [];
    $dh = opendir($realPath);
    while (($entry = readdir($dh)) !== false) {
        if ($entry === '.' || $entry === '..') continue;
        $full = $realPath . DIRECTORY_SEPARATOR . $entry;
        $stat = stat($full);
        $items[] = [
            'name' => $entry,
            'path' => $relPath ? $relPath . '/' . $entry : $entry,
            'is_dir' => is_dir($full),
            'size' => $stat['size'],
            'mtime' => $stat['mtime'],
            'mime' => is_dir($full) ? 'directory' : (mime_content_type($full) ?: 'application/octet-stream'),
        ];
    }
    closedir($dh);

    // 排序:目錄優先,再按名稱
    usort($items, fn($a, $b) => ($a['is_dir'] === $b['is_dir']) ? strcmp($a['name'], $b['name']) : ($b['is_dir'] ? 1 : -1));

    // JSON 回應 (供前端 AJAX)
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'current' => $relPath,
        'parent' => $relPath ? dirname($relPath) : null,
        'items' => $items,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

function downloadFile(string $realPath): void {
    if (!is_file($realPath)) { http_response_code(404); die('檔案不存在'); }
    $mime = mime_content_type($realPath) ?: 'application/octet-stream';
    $name = basename($realPath);
    header('Content-Type: ' . $mime);
    header('Content-Disposition: attachment; filename="' . rawurlencode($name) . '"');
    header('Content-Length: ' . filesize($realPath));
    header('X-Content-Type-Options: nosniff');
    readfile($realPath);
}

function deleteFile(string $realPath): void {
    if (!is_file($realPath) && !is_dir($realPath)) { http_response_code(404); die('不存在'); }
    $ok = is_file($realPath) ? unlink($realPath) : rmdir($realPath); // 目錄需為空
    header('Content-Type: application/json');
    echo json_encode(['success' => $ok, 'message' => $ok ? '刪除成功' : '刪除失敗 (目錄非空或無權限)']);
}

function uploadFile(string $realPath): void {
    if (!is_dir($realPath)) { http_response_code(400); die('目標非目錄'); }
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        http_response_code(400);
        die(json_encode(['success' => false, 'message' => '上傳失誤: ' . ($_FILES['file']['error'] ?? '未知')]));
    }
    $f = $_FILES['file'];
    if ($f['size'] > MAX_UPLOAD_SIZE) { http_response_code(413); die(json_encode(['success'=>false, 'message'=>'檔案過大'])); }
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $f['tmp_name']);
    finfo_close($finfo);
    if (!in_array($mime, ALLOWED_MIMES, true)) { http_response_code(415); die(json_encode(['success'=>false, 'message'=>'檔案類型不允許'])); }

    $ext = pathinfo($f['name'], PATHINFO_EXTENSION);
    $safeName = bin2hex(random_bytes(8)) . ($ext ? '.' . $ext : '');
    $dest = $realPath . DIRECTORY_SEPARATOR . $safeName;

    if (!move_uploaded_file($f['tmp_name'], $dest)) {
        http_response_code(500);
        die(json_encode(['success'=>false, 'message'=>'移動檔案失敗']));
    }
    @chmod($dest, 0644);
    header('Content-Type: application/json');
    echo json_encode(['success'=>true, 'name'=>$safeName, 'original'=>$f['name'], 'size'=>$f['size'], 'mime'=>$mime]);
}

function makeDirectory(string $realPath): void {
    $dirName = basename($_POST['name'] ?? '');
    if ($dirName === '' || preg_match('/[\\\\\/:*?"<>|]/', $dirName)) {
        http_response_code(400); die(json_encode(['success'=>false, 'message'=>'非法目錄名']));
    }
    $newDir = $realPath . DIRECTORY_SEPARATOR . $dirName;
    if (file_exists($newDir)) { http_response_code(409); die(json_encode(['success'=>false, 'message'=>'已存在'])); }
    $ok = mkdir($newDir, 0755, true);
    header('Content-Type: application/json');
    echo json_encode(['success'=>$ok, 'message'=>$ok?'建立成功':'建立失敗']);
}
?>

前端介面 (Vue 3 + Vite 簡易版)

<!-- index.html -->
<div id="app">
  <nav class="breadcrumb">
    <a @click="navigate('')">根目錄</a>
    <template v-for="seg in pathSegments" :key="seg.path">
      / <a @click="navigate(seg.path)">{{ seg.name }}</a>
    </template>
  </nav>

  <div class="toolbar">
    <input type="file" id="fileInput" @change="upload" ref="fileInput" style="display:none">
    <button @click="$refs.fileInput.click()">上傳檔案</button>
    <button @click="promptMkdir">新建資料夾</button>
  </div>

  <table class="file-table">
    <thead><tr><th>名稱</th><th>大小</th><th>修改時間</th><th>操作</th></tr></thead>
    <tbody>
      <tr v-for="item in items" :key="item.path">
        <td>
          <span v-if="item.is_dir" @click="navigate(item.path)" class="folder">📁 {{ item.name }}</span>
          <span v-else class="file">📄 {{ item.name }}</span>
        </td>
        <td v-if="!item.is_dir">{{ formatSize(item.size) }}</td>
        <td>{{ formatDate(item.mtime) }}</td>
        <td>
          <a v-if="!item.is_dir" :href="`/file.php?action=download&path=${item.path}`">下載</a>
          <button @click="deleteItem(item.path)" class="danger">刪除</button>
        </td>
      </tr>
    </tbody>
  </table>
</div>

<script type="module">
import { createApp, ref, computed, onMounted } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';

createApp({
  setup() {
    const path = ref('');
    const items = ref([]);
    const pathSegments = computed(() => {
      if (!path.value) return [];
      const segs = path.value.split('/');
      return segs.map((seg, i) => ({
        name: seg,
        path: segs.slice(0, i+1).join('/')
      }));
    });

    const load = async () => {
      const res = await fetch(`/file.php?action=list&path=${encodeURIComponent(path.value)}`);
      const data = await res.json();
      path.value = data.current;
      items.value = data.items;
    };

    const navigate = (p) => { path.value = p; load(); };
    const upload = async (e) => {
      const file = e.target.files[0]; if (!file) return;
      const fd = new FormData(); fd.append('file', file);
      const res = await fetch(`/file.php?action=upload&path=${encodeURIComponent(path.value)}`, {method:'POST', body:fd});
      const data = await res.json(); if (data.success) load(); else alert(data.message);
      e.target.value = '';
    };
    const promptMkdir = async () => {
      const name = prompt('資料夾名稱:'); if (!name) return;
      const res = await fetch(`/file.php?action=mkdir&path=${encodeURIComponent(path.value)}`, {method:'POST', body:new URLSearchParams({name})});
      const data = await res.json(); if (data.success) load(); else alert(data.message);
    };
    const deleteItem = async (p) => { if (!confirm('確定刪除?')) return; const res = await fetch(`/file.php?action=delete&path=${encodeURIComponent(p)}`, {method:'POST'}); const data = await res.json(); if (data.success) load(); else alert(data.message); };

    const formatSize = (b) => b < 1024 ? b+'B' : b < 1024*1024 ? (b/1024).toFixed(1)+'KB' : (b/1024/1024).toFixed(1)+'MB';
    const formatDate = (ts) => new Date(ts*1000).toLocaleString();

    onMounted(load);
    return { path, items, pathSegments, navigate, upload, promptMkdir, deleteItem, formatSize, formatDate };
  }
}).mount('#app');
</script>

定時備份腳本 (搭配 cron)

#!/bin/bash
# /usr/local/bin/backup_files.sh
SRC="/var/www/html/storage"
DEST="/backups/files/$(date +%F_%H-%M-%S).tar.gz"
tar -czf "$DEST" -C "$(dirname "$SRC")" "$(basename "$SRC")"
# 保留最近 30 天
find /backups/files -name '*.tar.gz' -mtime +30 -delete

加入 crontab:0 2 * * * /usr/local/bin/backup_files.sh (每天凌晨 2 點備份)

進階功能擴充建議

  • 圖片縮圖預覽 (GD/Imagick 即時生成或預生成)
  • 線上編輯文字檔 (CodeMirror/Monaco Editor)
  • ZIP 打包下載 (ZipArchive)
  • 全文搜索 (Meilisearch / Elasticsearch)
  • 權限控管 (ACL、角色、共享連結、密碼保護)
  • WebDAV 支援 (SabreDAV) 讓系統像網路磁碟一樣掛載
copyright © 萬盛學電腦網 all rights reserved