萬盛學電腦網

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

PHP cURL CURLOPT_POSTFIELDS 陷阱:陣列會觸發 multipart/form-data

現象

使用 cURL 發送 POST 請求時,若 CURLOPT_POSTFIELDS 直接傳入**陣列**,cURL 會將 Content-Type 設為 multipart/form-data(含 boundary 邊界),而非預期的 application/x-www-form-urlencoded。部分老舊或嚴格的伺服器無法正確解析,導致 500 錯誤或 $_POST 為空。

錯誤示範

$postData = ['key1' => 'val1', 'key2' => 'val2'];
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// 實際發送 Header:
// Content-Type: multipart/form-data; boundary=------------------------abc123

正確做法:http_build_query()

$postData = ['key1' => 'val1', 'key2' => 'val2'];
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
// 實際發送 Header:
// Content-Type: application/x-www-form-urlencoded
// 體積更小、相容性最佳

官方文檔說明

If value is an array, the Content-Type header will be set to multipart/form-data.
(當值為陣列時,Content-Type 標頭將被設為 multipart/form-data。)

此設計是為了支援 @/path/to/file 檔案上傳語法,但非檔案上傳場景下反成負擔。

最佳實踐封裝

function curlPost(string $url, array $data, array $options = []): string {
    $ch = curl_init($url);
    curl_setopt_array($ch, array_merge([
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($data), // 關鍵!
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => true, // 生產環境保持 true
    ], $options));
    $response = curl_exec($ch);
    if ($response === false) {
        throw new RuntimeException('cURL error: ' . curl_error($ch));
    }
    curl_close($ch);
    return $response;
}

補充:檔案上傳才用陣列 + CURLFile

$data = [
    'file' => new CURLFile('/path/to/image.png', 'image/png', 'avatar.png'),
    'username' => 'john',
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 此處正確使用陣列觸發 multipart
copyright © 萬盛學電腦網 all rights reserved