萬盛學電腦網

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

PHP 文件上傳完整實戰指南:從基礎到生產級安全

PHP 文件上傳核心流程與安全加固

文件上傳是 Web 應用高風險功能。本文涵蓋上傳流程、$_FILES 詳解、驗證策略、安全防護、大文件分片、雲存儲對接等生產級完整方案。

一、上傳核心流程與 $_FILES 結構

HTML 表單必要條件

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="2097152"> <!-- 2MB,客戶端提示,非強制 -->
    <input type="file" name="avatar" accept="image/*">
    <button type="submit">上傳頭像</button>
</form>

關鍵點:enctype="multipart/form-data"、method="post"、MAX_FILE_SIZE 僅客戶端提示。

$_FILES 結構詳解

<?php
// 單文件上傳
$_FILES['avatar'] = [
    'name'     => 'photo.jpg',           // 原始文件名(用戶可控,不可信)
    'type'     => 'image/jpeg',          // MIME 類型(瀏覽器提供,不可信)
    'tmp_name' => '/tmp/phpA1B2C3',      // 臨時文件路徑(服務器生成,可信)
    'size'     => 102400,                // 文件大小(字節)
    'error'    => UPLOAD_ERR_OK,         // 錯誤代碼
];

// 多文件上傳(name="files[]")
$_FILES['files'] = [
    'name'     => ['photo1.jpg', 'photo2.png'],
    'type'     => ['image/jpeg', 'image/png'],
    'tmp_name' => ['/tmp/phpA1B2C3', '/tmp/phpD4E5F6'],
    'size'     => [102400, 204800],
    'error'    => [UPLOAD_ERR_OK, UPLOAD_ERR_OK],
];
?>

上傳錯誤代碼對照表

常量值說明
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缺少臨時目錄
UPLOAD_ERR_CANT_WRITE7寫入磁盤失敗
UPLOAD_ERR_EXTENSION8PHP 擴展阻止上傳

二、基礎上傳處理代碼

<?php
function handleUpload(array $file, string $uploadDir, array $allowedTypes = [], int $maxSize = 2097152): array {
    // 1. 檢查錯誤
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'message' => '上傳錯誤:' . $file['error']];
    }
    
    // 2. 檢查文件大小
    if ($file['size'] > $maxSize) {
        return ['success' => false, 'message' => '文件過大,最大 ' . formatBytes($maxSize)];
    }
    
    // 3. 檢查 MIME 類型(僅作為初步過濾)
    if ($allowedTypes && !in_array($file['type'], $allowedTypes, true)) {
        return ['success' => false, 'message' => '不支持的文件類型'];
    }
    
    // 4. 安全檢查:真實 MIME 類型(需 fileinfo 擴展)
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $realMime = $finfo->file($file['tmp_name']);
    if ($allowedTypes && !in_array($realMime, $allowedTypes, true)) {
        return ['success' => false, 'message' => '文件內容類型不匹配'];
    }
    
    // 5. 生成安全文件名
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $safeName = bin2hex(random_bytes(16)) . ($ext ? '.' . strtolower($ext) : '');
    $destPath = $uploadDir . DIRECTORY_SEPARATOR . $safeName;
    
    // 6. 確保上傳目錄存在
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // 7. 移動文件(原子操作)
    if (!move_uploaded_file($file['tmp_name'], $destPath)) {
        return ['success' => false, 'message' => '文件移動失敗'];
    }
    
    // 8. 設置安全權限
    chmod($destPath, 0644);
    
    return [
        'success' => true,
        'filename' => $safeName,
        'original_name' => $file['name'],
        'path' => $destPath,
        'size' => $file['size'],
        'mime' => $realMime,
    ];
}

function formatBytes(int $bytes): string {
    $units = ['B', 'KB', 'MB', 'GB'];
    $pow = floor($bytes ? log($bytes, 1024) : 0);
    $pow = min($pow, count($units) - 1);
    return round($bytes / (1024 ** $pow), 2) . ' ' . $units[$pow];
}

// 使用範例
$result = handleUpload(
    $_FILES['avatar'],
    __DIR__ . '/uploads/avatars',
    ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
    5 * 1024 * 1024 // 5MB
);

header('Content-Type: application/json');
echo json_encode($result);
?>

三、安全防護深度加固

1. 文件類型驗證三重門

<?php
function validateFileType(string $tmpPath, array $allowedMimes): bool {
    // 第一層:fileinfo 擴展(最可靠)
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($tmpPath);
    if (!in_array($mime, $allowedMimes, true)) return false;
    
    // 第二層:圖片專用 getimagesize() 驗證
    if (str_starts_with($mime, 'image/')) {
        $info = @getimagesize($tmpPath);
        if ($info === false) return false; // 不是有效圖片
        // $info[2] 對應 IMAGETYPE_* 常量
        $allowedImageTypes = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP];
        if (!in_array($info[2], $allowedImageTypes, true)) return false;
    }
    
    // 第三層:擴展名白名單(輔助)
    $ext = strtolower(pathinfo($tmpPath, PATHINFO_EXTENSION));
    $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'];
    if (!in_array($ext, $allowedExt, true)) return false;
    
    return true;
}
?>

2. 防止腳本執行攻擊

  • 上傳目錄禁用腳本執行(Nginx/Apache 配置)
  • 文件重命名:隨機名 + 白名單擴展名
  • 存儲路徑非 Web 可訪問:放在 public 目錄外,通過 PHP 讀取輸出
  • Content-Security-Policy:響應頭禁止內聯腳本
# Nginx 禁止上傳目錄執行 PHP
location /uploads/ {
    location ~ \.php$ {
        deny all;
        return 403;
    }
}

# Apache .htaccess

    Order Allow,Deny
    Deny from all

3. 文件內容掃描(病毒/惡意代碼)

<?php
// 集成 ClamAV 掃描(需安裝 clamav-daemon 和 php-clamav 擴展)
function scanVirus(string $filePath): bool {
    if (!extension_loaded('clamav')) return true; // 無掃描器視為通過
    
    $clamav = new ClamAV();
    $result = $clamav->scan($filePath);
    return $result === 0; // 0 = 乾淨
}

// 或調用命令行掃描
function scanVirusCli(string $filePath): bool {
    $output = [];
    $returnVar = 0;
    exec("clamscan --no-summary " . escapeshellarg($filePath), $output, $returnVar);
    return $returnVar === 0;
}
?>

四、大文件分片上傳(斷點續傳)

前端分片邏輯(JavaScript 伪代碼)

// 1. 計算文件 hash(Web Worker 避免阻塞)
const fileHash = await calculateHash(file, 'md5');

// 2. 檢查服務器是否已有分片/秒傳
const { uploadedChunks } = await api.checkChunks(fileHash);

// 3. 分片上傳
const chunkSize = 5 * 1024 * 1024; // 5MB
for (let start = 0; start < file.size; start += chunkSize) {
    const chunkIndex = Math.floor(start / chunkSize);
    if (uploadedChunks.includes(chunkIndex)) continue; // 跳過已上傳
    
    const chunk = file.slice(start, start + chunkSize);
    const formData = new FormData();
    formData.append('file', chunk);
    formData.append('hash', fileHash);
    formData.append('chunk', chunkIndex);
    formData.append('chunks', Math.ceil(file.size / chunkSize));
    
    await api.uploadChunk(formData);
}

// 4. 合併請求
await api.mergeChunks(fileHash, file.name);

PHP 合併分片

<?php
function mergeChunks(string $hash, string $filename, int $totalChunks, string $tempDir, string $destDir): array {
    $finalPath = $destDir . DIRECTORY_SEPARATOR . $hash . '_' . basename($filename);
    $finalHandle = fopen($finalPath, 'wb');
    
    for ($i = 0; $i < $totalChunks; $i++) {
        $chunkPath = $tempDir . DIRECTORY_SEPARATOR . $hash . ".part$i";
        if (!is_file($chunkPath)) {
            fclose($finalHandle);
            unlink($finalPath);
            return ['success' => false, 'message' => "分片 $i 缺失"];
        }
        $chunkHandle = fopen($chunkPath, 'rb');
        stream_copy_to_stream($chunkHandle, $finalHandle);
        fclose($chunkHandle);
        unlink($chunkPath); // 清理分片
    }
    fclose($finalHandle);
    
    // 驗證完整性
    // $expectedHash = hash_file('md5', $finalPath);
    // if ($expectedHash !== $hash) { unlink($finalPath); return ['success' => false, 'message' => '完整性校驗失敗']; }
    
    return ['success' => true, 'path' => $finalPath];
}
?>

五、雲存儲對接(以阿里云 OSS 為例)

<?php
// composer require aliyuncs/oss-sdk-php
use OSS\OssClient;
use OSS\Core\OssException;

class OssUploader {
    private OssClient $client;
    private string $bucket;
    
    public function __construct(string $accessKeyId, string $accessKeySecret, string $endpoint, string $bucket) {
        $this->client = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $this->bucket = $bucket;
    }
    
    public function upload(string $object, string $filePath, array $options = []): string {
        try {
            $this->client->uploadFile($this->bucket, $object, $filePath, $options);
            return $this->client->signUrl($this->bucket, $object, 3600); // 簽名 URL
        } catch (OssException $e) {
            throw new \RuntimeException('OSS 上傳失敗:' . $e->getMessage());
        }
    }
    
    // 直傳簽名(前端直傳 OSS,減輕服務器壓力)
    public function getUploadPolicy(string $dir, int $expire = 3600): array {
        $policy = base64_encode(json_encode([
            'expiration' => date('c', time() + $expire),
            'conditions' => [
                ['content-length-range', 0, 10 * 1024 * 1024],
                ['starts-with', '$key', $dir],
            ],
        ]));
        $signature = base64_encode(hash_hmac('sha1', $policy, $this->client->getAccessKeySecret(), true));
        
        return [
            'policy' => $policy,
            'signature' => $signature,
            'access_key_id' => $this->client->getAccessKeyId(),
            'host' => "https://{$this->bucket}.{$this->client->getEndpoint()}",
            'dir' => $dir,
            'expire' => $expire,
        ];
    }
}
?>

六、php.ini 關鍵配置

; 文件上傳總開關
file_uploads = On

; 臨時目錄(需可寫)
upload_tmp_dir = /tmp/php_uploads

; 最大上傳文件大小(單文件)
upload_max_filesize = 50M

; POST 最大大小(需 >= upload_max_filesize)
post_max_size = 60M

; 最大文件數量
max_file_uploads = 20

; 腳本執行時間(大文件需調大)
max_execution_time = 300
max_input_time = 300

; 內存限制
memory_limit = 256M

七、錯誤處理與用戶體驗優化

<?php
// 統一異常處理
try {
    $result = handleUpload($_FILES['file'], $uploadDir, $allowedTypes, $maxSize);
    
    if (!$result['success']) {
        throw new \RuntimeException($result['message']);
    }
    
    // 記錄上傳日志
    logUpload($result, $_SERVER['REMOTE_ADDR']);
    
    // API 響應
    jsonResponse(['success' => true, 'data' => $result]);
    
} catch (\Throwable $e) {
    // 記錄錯誤日志
    error_log('上傳失敗:' . $e->getMessage());
    
    // 用戶友好提示(不暴露內部細節)
    $userMessage = match(true) {
        str_contains($e->getMessage(), '大小') => '文件過大,請壓縮後重試',
        str_contains($e->getMessage(), '類型') => '不支持的文件格式',
        default => '上傳失敗,請稍後重試'
    };
    
    jsonResponse(['success' => false, 'message' => $userMessage], 400);
}

function jsonResponse(array $data, int $status = 200): never {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit();
}
?>
copyright © 萬盛學電腦網 all rights reserved