萬盛學電腦網

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

PHP cURL 兩大 POST 提交方式深度解析:multipart/form-data vs application/x-www-form-urlencoded

核心差異一覽

特性multipart/form-dataapplication/x-www-form-urlencoded
Content-Typemultipart/form-data; boundary=----WebKitFormBoundary...application/x-www-form-urlencoded
資料編碼每欄位獨立 Part,含 Header+Body,支援二進位檔案鍵值對 URL 編碼 key1=val1&key2=val2
檔案上傳✅ 原生支援❌ 不支援 (需 Base64 編碼放入欄位)
PHP cURL 預設**陣列傳給 CURLOPT_POSTFIELDS 時自動使用**需手動 http_build_query() + 設定 Header
適用場景檔案上傳、混合表單、非 ASCII 資料純文字鍵值對、API 呼叫、傳統表單提交
伺服端解析PHP $_FILES + $_POSTPHP $_POST (自動解析)

方式一:multipart/form-data (cURL 預設、檔案上傳首選)

<?php
function postMultipart(string $url, array $fields, array $files = [], array $options = []): string {
    $ch = curl_init();
    
    // 處理檔案上傳:CURLFile 物件 (PHP 5.5+)
    $postData = $fields;
    foreach ($files as $key => $path) {
        if (!is_file($path)) throw new \InvalidArgumentException("File not found: $path");
        $mime = mime_content_type($path) ?: 'application/octet-stream';
        $postData[$key] = new CURLFile($path, $mime, basename($path));
    }
    
    $defaultOptions = [
        CURLOPT_URL            => $url,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $postData, // 陣列含 CURLFile → 自動 multipart
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => true,  // 生產環境必須 true
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT      => 'PHP-cURL/'.phpversion(),
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_HEADER         => false,
    ];
    
    curl_setopt_array($ch, $defaultOptions + $options);
    
    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    
    if ($errno) throw new \RuntimeException("cURL error ($errno): $error");
    if ($info['http_code'] >= 400) throw new \RuntimeException("HTTP {$info['http_code']}");
    
    return $response;
}

// 使用範例:上傳頭像
$response = postMultipart(
    'https://api.example.com/upload',
    ['user_id' => 123, 'description' => 'avatar'],
    ['avatar' => '/tmp/avatar.png']
);

方式二:application/x-www-form-urlencoded (API 呼叫、傳統表單)

<?php
function postFormUrlEncoded(string $url, array $data, array $options = []): string {
    $ch = curl_init();
    
    $defaultOptions = [
        CURLOPT_URL            => $url,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($data), // 關鍵:陣列轉查詢字串
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json',
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT      => 'PHP-cURL/'.phpversion(),
        CURLOPT_TIMEOUT        => 30,
    ];
    
    curl_setopt_array($ch, $defaultOptions + $options);
    
    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    
    if ($errno) throw new \RuntimeException("cURL error ($errno): $error");
    if ($info['http_code'] >= 400) throw new \RuntimeException("HTTP {$info['http_code']}");
    
    return $response;
}

// 使用範例:OAuth2 取得 token
$tokenResponse = postFormUrlEncoded(
    'https://auth.example.com/oauth/token',
    [
        'grant_type'    => 'client_credentials',
        'client_id'     => 'my_client_id',
        'client_secret' => 'super_secret',
        'scope'         => 'read write',
    ]
);
$tokenData = json_decode($tokenResponse, true);

關鍵技術細節

1. 為什麼陣列直接給 CURLOPT_POSTFIELDS 會變 multipart?

cURL 內部邏輯:CURLOPT_POSTFIELDS 接收**陣列** → 自動構建 multipart/form-data;接收**字串** → 直接發送字串內容,**不自動加 Header**。

2. http_build_query() 細節

<?php
$data = ['arr' => [1,2,3], 'obj' => (object)['a'=>1]];
// PHP 5.3+ 預設使用 PHP_QUERY_RFC3986 (RFC 3986 標準編碼)
// 空格編碼為 %20 (非 +)
// 巢狀陣列編碼為 arr[0]=1&arr[1]=2&arr[2]=3
// 物件轉為陣列後編碼
echo http_build_query($data);
// arr%5B0%5D=1&arr%5B1%5D=2&arr%5B2%5D=3&obj%5Ba%5D=1

3. 檔案上傳舊寫法 (已棄用、不安全)

<?php
// ❌ PHP 5.5 前舊寫法:@ 開頭路徑
$postData['file'] = '@/path/to/file.png'; // 僅在 CURLOPT_SAFE_UPLOAD=false 時生效

// ✅ 現代寫法:CURLFile 物件
$postData['file'] = new CURLFile('/path/to/file.png', 'image/png', 'file.png');

// ⚠️ 關閉舊式上傳 (PHP 5.6+ 預設關閉)
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); // 預設 true,防止 @ 註入攻擊

4. 邊界字串

multipart 請求會自動生成隨機 boundary,分隔各 Part。伺服端解析器依據 boundary 切分。無需手動設定。

常見錯誤與除錯

現象原因解決
$_POST 為空、$_FILES 為空Content-Type 錯誤或未設定檢查 CURLOPT_HTTPHEADER、確認 http_build_query vs 陣列
檔案上傳失敗 400/500CURLFile 路徑錯誤、MIME 類型不支援、檔案過大驗證 is_file()、filesize()、伺服端上傳限制
中文亂碼編碼不一致確保檔案 UTF-8、http_build_query 預設 UTF-8、Header charset=utf-8
SSL 憑證驗證失敗CA 憑證缺失設定 CURLOPT_CAINFO 指向 cacert.pem
超時網路/伺服端慢調大 CURLOPT_TIMEOUT/CURLOPT_CONNECTTIMEOUT

進階:統一 HTTP 客戶端封裝 (支援兩種 POST + GET/PUT/DELETE)

<?php
class HttpClient {
    private $ch;
    
    public function __construct() {
        $this->ch = curl_init();
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_USERAGENT      => 'MyApp/1.0 (PHP-cURL)',
            CURLOPT_TIMEOUT        => 30,
        ]);
    }
    
    public function request(string $method, string $url, array $data = [], array $headers = [], bool $multipart = false): array {
        $opts = [CURLOPT_URL => $url, CURLOPT_CUSTOMREQUEST => strtoupper($method)];
        
        if ($multipart) {
            // 檔案欄位自動轉 CURLFile
            foreach ($data as $k => $v) {
                if ($v instanceof \SplFileInfo) {
                    $data[$k] = new \CURLFile($v->getRealPath(), $v->getMimeType(), $v->getFilename());
                }
            }
            $opts[CURLOPT_POSTFIELDS] = $data;
        } elseif (in_array($method, ['POST', 'PUT', 'PATCH'])) {
            $opts[CURLOPT_POSTFIELDS] = http_build_query($data);
            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
        }
        
        if ($headers) $opts[CURLOPT_HTTPHEADER] = $headers;
        
        curl_setopt_array($this->ch, $opts);
        $response = curl_exec($this->ch);
        $info = curl_getinfo($this->ch);
        
        if (curl_errno($this->ch)) {
            throw new \RuntimeException(curl_error($this->ch), curl_errno($this->ch));
        }
        
        return [
            'status' => $info['http_code'],
            'headers' => $this->parseHeaders($info['header_size'] ?? 0),
            'body' => $response,
            'json' => json_decode($response, true),
        ];
    }
    
    private function parseHeaders(int $headerSize): array { /* 解析回應 Header */ return []; }
    
    public function __destruct() { curl_close($this->ch); }
}

// 使用
$client = new HttpClient();
$res = $client->request('POST', 'https://api.example.com/users', ['name' => 'Tom']);
$res = $client->request('POST', 'https://api.example.com/upload', ['file' => new SplFileInfo('/tmp/a.png')], [], true);

總結選擇指南

  1. 需上傳檔案 / 混合表單 → **multipart/form-data** (cURL 陣列模式自動處理)。
  2. 純鍵值對 API / OAuth / 傳統表單 → **application/x-www-form-urlencoded** (http_build_query + Header)。
  3. JSON API → 非表單類型,用 Content-Type: application/json + json_encode。
  4. 永遠啟用 SSL 驗證 (生產環境),配置 CURLOPT_CAINFO。
  5. 封裝統一 HttpClient,集中管理錯誤處理、重試、日誌、超時、認證。
copyright © 萬盛學電腦網 all rights reserved