使用 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;
}
$data = [
'file' => new CURLFile('/path/to/image.png', 'image/png', 'avatar.png'),
'username' => 'john',
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 此處正確使用陣列觸發 multipart