萬盛學電腦網

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

PHP 多檔案上傳下載完整系統:上傳、列表、下載一站式範例

系統架構概覽

  • index_uploads.php - 上傳表單頁面
  • uploads.php - 處理上傳、轉向列表頁
  • listdir.php - 顯示檔案列表、提供下載連結
  • download.php - 強制下載檔案

1. 上傳表單 index_uploads.php

<!DOCTYPE html>
<html><head><meta charset=\"utf-8\"><title>檔案上傳</title></head>
<body>
<form action=\"uploads.php\" method=\"post\" enctype=\"multipart/form-data\">
    <input type=\"file\" name=\"file[]\" multiple><br>
    <input type=\"submit\" value=\"上傳檔案\">
</form>
</body></html>

2. 上傳處理 uploads.php

<?php
header('Content-Type: text/html; charset=utf-8');

$uploadDir = __DIR__ . '/uploads/files/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

$count = count($_FILES['file']['name']);
$success = 0;

for ($i = 0; $i < $count; $i++) {
    if ($_FILES['file']['error'][$i] !== UPLOAD_ERR_OK) continue;
    
    $tmpName = $_FILES['file']['tmp_name'][$i];
    $ext = strtolower(pathinfo($_FILES['file']['name'][$i], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','gif','pdf','txt','zip'];
    
    if (!in_array($ext, $allowed)) continue;
    
    $newName = date('YmdHis') . '_' . mt_rand(1000,9999) . '.' . $ext;
    $dest = $uploadDir . $newName;
    
    if (move_uploaded_file($tmpName, $dest)) $success++;
}

header('Location: listdir.php' . ($success ? '?msg=upload_ok' : '?msg=upload_fail'));
?>

3. 檔案列表 listdir.php

<?php
header('Content-Type: text/html; charset=utf-8');
$dir = __DIR__ . '/uploads/files/';

echo '<h2>檔案下載中心 | <a href=\"index_uploads.php\">上傳新檔案</a></h2>';
echo '<table border=\"1\" width=\"800\">';
echo '<tr><th>縮圖/圖示</th><th>檔名</th><th>大小</th><th>修改時間</th><th>操作</th></tr>';

$items = scandir($dir);
foreach ($items as $file) {
    if ($file === '.' || $file === '..') continue;
    $path = $dir . $file;
    if (!is_file($path)) continue;
    
    $size = filesize($path);
    $mtime = date('Y-m-d H:i:s', filemtime($path));
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $isImage = in_array($ext, ['jpg','jpeg','png','gif']);
    
    echo '<tr>';
    echo '<td style=\"text-align:center\">';
    if ($isImage) {
        echo '<img src=\"download.php?file=' . urlencode($file) . '&thumb=1\" width=\"80\">';
    } else {
        echo '📄';
    }
    echo '</td>';
    echo '<td>' . htmlspecialchars($file) . '</td>';
    echo '<td>' . formatBytes($size) . '</td>';
    echo '<td>' . $mtime . '</td>';
    echo '<td><a href=\"download.php?file=' . urlencode($file) . '\">下載</a> | ';
    echo '<a href=\"delete.php?file=' . urlencode($file) . '\" onclick=\"return confirm(\'確定刪除?\')\">刪除</a></td>';
    echo '</tr>';
}
echo '</table>';

function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $i = 0;
    while ($bytes >= 1024 && $i < count($units) - 1) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, $precision) . ' ' . $units[$i];
}
?>

4. 下載處理 download.php(核心)

<?php
$file = basename($_GET['file'] ?? ''); // 防路徑遍歷
$path = __DIR__ . '/uploads/files/' . $file;

if (!is_file($path)) {
    header('HTTP/1.1 404 Not Found');
    exit('檔案不存在');
}

$size = filesize($path);
$mime = mime_content_type($path);

// 縮圖模式(僅圖片)
if (isset($_GET['thumb']) && strpos($mime, 'image/') === 0) {
    // 這裡可加入縮圖生成邏輯,簡化直接輸出原圖
    header("Content-Type: $mime");
    header("Content-Length: $size");
    readfile($path);
    exit;
}

// 強制下載模式
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($file) . '"');
header('Content-Length: ' . $size);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Expires: 0');

readfile($path);
?>

核心下載標頭解析

Header作用
Content-Type: application/octet-stream告訴瀏覽器這是二進位檔案,不要嘗試在瀏覽器開啟
Content-Disposition: attachment; filename=\"...\"觸發「另存新檔」對話框,指定預設檔名
Content-Length讓瀏覽器顯示下載進度條
readfile()高效輸出檔案內容到輸出緩衝,不佔用 PHP 記憶體

安全性補強

  • basename() 防止 ../../etc/passwd 路徑遍歷攻擊。
  • 下載目錄設為 Web 根目錄外,或 Nginx 設定 internal 只允許內部重導向存取。
  • 大檔案支援 X-Sendfile (Apache) / X-Accel-Redirect (Nginx) 讓 Web Server 直接傳輸,釋放 PHP 進程。
copyright © 萬盛學電腦網 all rights reserved