萬盛學電腦網

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

PHP 批量圖片上傳完整實作(HTML 表單 + 後端處理)

PHP 多檔案上傳核心技術:name="pictures[]"

HTML 表單中將多個 <input type="file"> 的 name 設為陣列格式 pictures[],PHP 端 $_FILES['pictures'] 即為多維陣列,配合迴圈即可批量處理。

前端表單

<form action="" method="post" enctype="multipart/form-data">
    Pictures:<br/>
    <input type="file" name="pictures[]" /><br/>
    <input type="file" name="pictures[]" /><br/>
    <input type="file" name="pictures[]" /><br/>
    <input type="submit" name="upload" value="Send" />
</form>

後端處理

<?php
if ($_POST['upload'] === 'Send') {
    $dest = 'picture/';
    if (!file_exists($dest)) mkdir($dest, 0755, true);

    foreach ($_FILES['pictures']['error'] as $key => $error) {
        if ($error === UPLOAD_ERR_OK) {
            $tmp = $_FILES['pictures']['tmp_name'][$key];
            $name = $_FILES['pictures']['name'][$key];
            $target = $dest . basename($name); // 防止路徑遍歷
            if (move_uploaded_file($tmp, $target)) {
                echo "上傳成功:$name<br/>";
            } else {
                echo "移動失敗:$name<br/>";
            }
        } elseif ($error === UPLOAD_ERR_NO_FILE) {
            continue; // 該欄位未選檔案
        } else {
            echo "錯誤代碼 $error:$name<br/>";
        }
    }
}
?>

關鍵陣列結構說明

$_FILES['pictures'] = [
    'name'     => ['a.jpg', 'b.png', 'c.gif'],
    'type'     => ['image/jpeg', 'image/png', 'image/gif'],
    'tmp_name' => ['/tmp/phpX1', '/tmp/phpX2', '/tmp/phpX3'],
    'error'    => [0, 0, 0],
    'size'     => [12345, 23456, 34567],
];

安全與健壯性加強

  1. 檔案類型驗證:用 finfo_file() 檢測 MIME,不要只信副檔名
  2. 檔名安全:重新命名(如 uniqid() . '.' . pathinfo($name, PATHINFO_EXTENSION))
  3. 大小限制:$_FILES['pictures']['size'][$key] < MAX_SIZE
  4. 目錄權限:上傳目錄**不可**有執行權限,Nginx/Apache 設定禁用腳本執行
  5. 錯誤碼處理:完整對照 UPLOAD_ERR_* 常數

現代化建議

  • 前端採用 input[multiple] 或拖曳上傳(Dropzone.js、Uppy)
  • 後端使用 PSR-7 UploadedFile 介面(如 nyholm/psr7)
  • 大檔案採分片上傳 + 斷點續傳
copyright © 萬盛學電腦網 all rights reserved