對接第三方 API、微服務間通訊、Webhook 回調,POST 請求是最常見的互動方式。cURL 作為 PHP 最強大的 HTTP 客戶端,支援完整的協議特性。本文提供標準化封裝與關鍵參數詳解。
<?php
/**
* 發送 POST 請求並回傳解碼後的關聯陣列
*
* @param string $url 目標 URL
* @param array $data POST 欄位(自動 application/x-www-form-urlencoded)
* @param array $options 額外 cURL 選項(會合併覆蓋預設值)
* @return array|null 成功回傳關聯陣列,失敗回傳 null 並記錄錯誤
*/
function postApi(string $url, array $data = [], array $options = []): ?array
{
$ch = curl_init();
$defaultOptions = [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10, // 總超時 10 秒
CURLOPT_CONNECTTIMEOUT => 3, // 連線超時 3 秒
CURLOPT_HTTPHEADER => [
'User-Agent: MyApp/1.0 (PHP/cURL)',
'Accept: application/json',
],
CURLOPT_SSL_VERIFYPEER => true, // 生產環境必須驗證憑證
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
];
curl_setopt_array($ch, $defaultOptions + $options);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($errno) {
error_log("cURL POST error [$errno]: $error | URL: $url");
return null;
}
if ($httpCode < 200 || $httpCode >= 300) {
error_log("HTTP $httpCode from $url | Response: $response");
return null;
}
$decoded = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("JSON decode failed: " . json_last_error_msg() . " | Raw: $response");
return null;
}
return $decoded;
}
| 場景 | 關鍵參數設定 |
|---|---|
| 發送 JSON Body | CURLOPT_POSTFIELDS => json_encode($data) + CURLOPT_HTTPHEADER => ['Content-Type: application/json'] |
| 上傳檔案 | CURLOPT_POSTFIELDS => ['file' => new CURLFile('/path/to/file', 'image/png', 'name.png')](PHP 5.5+) |
| Bearer Token 驗證 | CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $accessToken] |
| 自訂憑證(雙向 TLS) | CURLOPT_SSLCERT, CURLOPT_SSLKEY, CURLOPT_CAINFO |
| 代理伺服器 | CURLOPT_PROXY => 'https://proxy:3128', CURLOPT_PROXYUSERPWD |
掌握 cURL 細節,讓 API 整合更穩健、可觀測、可維護。