萬盛學電腦網

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

PHP 多檔案上傳完整實作:HTML 表單與後端處理邏輯

前端表單:關鍵在 name=\"file[]\" 陣列語法

<!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[]\"><br>
        <input type=\"file\" name=\"file[]\"><br>
        <input type=\"file\" name=\"file[]\"><br>
        <input type=\"submit\" value=\"上傳檔案\">
    </form>
</body>
</html>

後端處理:$_FILES 陣列結構解析

多檔案上傳時,$_FILES['file'] 結構為:

Array
(
    [name]     => Array ( [0] => 'a.jpg', [1] => 'b.png', [2] => 'c.pdf' )
    [type]     => Array ( [0] => 'image/jpeg', [1] => 'image/png', [2] => 'application/pdf' )
    [tmp_name] => Array ( [0] => '/tmp/phpX123', [1] => '/tmp/phpY456', [2] => '/tmp/phpZ789' )
    [error]    => Array ( [0] => 0, [1] => 0, [2] => 0 )
    [size]     => Array ( [0] => 12345, [1] => 67890, [2] => 24680 )
)

完整上傳處理程式碼 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;
$errors = [];

for ($i = 0; $i < $count; $i++) {
    // 檢查上傳錯誤代碼
    if ($_FILES['file']['error'][$i] !== UPLOAD_ERR_OK) {
        $errors[] = "檔案 {$_FILES['file']['name'][$i]} 上傳失敗,錯誤代碼:{$_FILES['file']['error'][$i]}";
        continue;
    }
    
    $tmpName = $_FILES['file']['tmp_name'][$i];
    $origName = $_FILES['file']['name'][$i];
    
    // 安全性:驗證副檔名與 MIME 類型
    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx'];
    if (!in_array($ext, $allowedExt)) {
        $errors[] = "檔案 $origName 副檔名不允許($ext)";
        continue;
    }
    
    // 產生唯一檔名:時間戳_隨機數.副檔名
    $newName = time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
    $destPath = $uploadDir . $newName;
    
    // 移動上傳檔案
    if (move_uploaded_file($tmpName, $destPath)) {
        $success++;
    } else {
        $errors[] = "檔案 $origName 移動失敗";
    }
}

// 輸出結果
if ($success) {
    echo "";
}
if ($errors) {
    echo "";
}
?>

關鍵安全性檢查清單

  1. 檢查 error 代碼:UPLOAD_ERR_OK (0) 才處理。
  2. 驗證副檔名:白名單機制,拒絕 .php、.exe 等可執行檔。
  3. 驗證 MIME 類型:使用 finfo_file() 檢測真實類型,防偽裝副檔名。
  4. 限制檔案大小:$_FILES['file']['size'][$i] > $maxSize。
  5. 重新命名檔案:避免覆蓋、防路徑遍歷、避免中文檔名編碼問題。
  6. 上傳目錄權限:不可執行(Nginx/Apache 設定 location ~ \.php$ { deny all; })。
  7. 病毒掃描:生產環境建議整合 ClamAV 掃描。

HTML5 多檔案選取(單一 input)

<input type=\"file\" name=\"file[]\" multiple>

使用者可按住 Ctrl/Shift 選取多檔,$_FILES 結構相同,前端體驗更好。

copyright © 萬盛學電腦網 all rights reserved