萬盛學電腦網

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

PHP $_FILES 陣列完整解析:上傳檔案資訊、錯誤代碼與安全處理

$_FILES 結構詳解

表單需設定 `enctype="multipart/form-data"`,單檔上傳時結構如下:

$_FILES['myFile'] = [
    'name'     => 'photo.jpg',        // 客戶端原始檔名
    'type'     => 'image/jpeg',       // MIME 類型 (瀏覽器提供,不可信)
    'tmp_name' => '/tmp/phpA1B2C3',   // 伺服器暫存路徑
    'size'     => 123456,             // 檔案大小 (bytes)
    'error'    => 0,                  // 錯誤代碼
];

錯誤代碼對照表 (PHP 4.2.0+ 為常量)

常量值說明
UPLOAD_ERR_OK0上傳成功
UPLOAD_ERR_INI_SIZE1超過 php.ini `upload_max_filesize`
UPLOAD_ERR_FORM_SIZE2超過表單 `MAX_FILE_SIZE` 隱藏欄位
UPLOAD_ERR_PARTIAL3僅部分上傳 (網路中斷)
UPLOAD_ERR_NO_FILE4未選擇檔案
UPLOAD_ERR_NO_TMP_DIR6缺少暫存目錄 (PHP 5.0.3+)
UPLOAD_ERR_CANT_WRITE7寫入磁碟失敗 (PHP 5.1.0+)
UPLOAD_ERR_EXTENSION8擴展阻止上傳 (PHP 5.2.0+)

安全處理標準流程

<?php
function handleUpload(array $file, string $uploadDir, array $allowedMimes = []): array
{
    // 1. 錯誤檢查
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('上傳錯誤代碼: ' . $file['error']);
    }

    // 2. MIME 驗證 (使用 finfo,不可信 $_FILES['type'])
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);
    if ($allowedMimes && !in_array($mime, $allowedMimes, true)) {
        throw new RuntimeException('檔案類型不允許: ' . $mime);
    }

    // 3. 檔案大小二次檢查
    if ($file['size'] > 5 * 1024 * 1024) { // 5MB
        throw new RuntimeException('檔案過大');
    }

    // 4. 產生安全檔名
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $ext = strtolower($ext);
    $allowedExt = ['jpg','jpeg','png','gif','webp','pdf'];
    if (!in_array($ext, $allowedExt, true)) {
        throw new RuntimeException('副檔名不允許');
    }
    $newName = bin2hex(random_bytes(16)) . '.' . $ext;
    $destPath = $uploadDir . DIRECTORY_SEPARATOR . $newName;

    // 5. 移動檔案 (不可用 copy+unlink)
    if (!move_uploaded_file($file['tmp_name'], $destPath)) {
        throw new RuntimeException('移動檔案失敗');
    }

    // 6. 圖片二次渲染清理 (可選)
    if (str_starts_with($mime, 'image/')) {
        $im = imagecreatefromstring(file_get_contents($destPath));
        if ($im) {
            imagewebp($im, $destPath, 85);
            imagedestroy($im);
        }
    }

    return ['path' => $destPath, 'name' => $newName, 'mime' => $mime, 'size' => $file['size']];
}
?>

多檔案上傳

<?php
// 
foreach ($_FILES['files']['error'] as $key => $error) {
    if ($error === UPLOAD_ERR_OK) {
        $single = [
            'name'     => $_FILES['files']['name'][$key],
            'type'     => $_FILES['files']['type'][$key],
            'tmp_name' => $_FILES['files']['tmp_name'][$key],
            'size'     => $_FILES['files']['size'][$key],
            'error'    => $error,
        ];
        try {
            $result = handleUpload($single, __DIR__.'/uploads', ['image/jpeg','image/png','image/webp']);
            echo "成功: {$result['name']}
"; } catch (Throwable $e) { echo "失敗: {$e->getMessage()}
"; } } } ?>

配置優化 (php.ini)

file_uploads = On
upload_max_filesize = 10M
post_max_size = 12M
max_file_uploads = 20
upload_tmp_dir = /var/tmp/php-upload
; 確保目錄存在且 www-data 可寫
copyright © 萬盛學電腦網 all rights reserved