適用於簡單 GET/POST、無複雜認證、不想引入依賴的場景。
<?php
/**
* 發送 POST 請求(原生 stream_context)
* @param string $url 目標 URL
* @param array|string $data POST 數據(數組自動 http_build_query)
* @param array $headers 額外 Header
* @param int $timeout 總超時秒數
* @return string|false 響應體或 false
*/
function postRequest(string $url, $data, array $headers = [], int $timeout = 30) {
$body = is_array($data) ? http_build_query($data) : $data;
$defaultHeaders = [
'Content-Type: application/x-www-form-urlencoded',
'User-Agent: PHP-Stream/' . phpversion(),
];
$opts = [
'http' => [
'method' => 'POST',
'header' => implode("\r\n", array_merge($defaultHeaders, $headers)),
'content' => $body,
'timeout' => $timeout,
'ignore_errors' => true, // 獲取非 2xx 響應體
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
],
];
$context = stream_context_create($opts);
$response = @file_get_contents($url, false, $context);
// 獲取 HTTP 狀態碼
$statusLine = $http_response_header[0] ?? 'HTTP/1.0 000';
preg_match('/\d{3}/', $statusLine, $matches);
$httpCode = (int)($matches[0] ?? 0);
if ($response === false) {
error_log("POST $url failed: " . error_get_last()['message'] ?? 'unknown');
return false;
}
return ['code' => $httpCode, 'body' => $response, 'headers' => $http_response_header];
}
// 使用示例
$result = postRequest('https://api.example.com/notify', [
'event' => 'order_created',
'order_id' => 12345,
'amount' => 99.90,
]);
if ($result && $result['code'] === 200) {
$resp = json_decode($result['body'], true);
// 業務處理
}
?>
<?php
/**
* cURL 發送 POST(支援 HTTPS、代理、證書、多部分表單、並發)
*/
function postCurl(string $url, $data, array $headers = [], int $timeout = 30, array $curlOpts = []) {
$ch = curl_init();
$defaultOpts = [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => is_array($data) ? http_build_query($data) : $data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_HTTPHEADER => array_merge([
'Content-Type: application/x-www-form-urlencoded',
'User-Agent: PHP-cURL/' . curl_version()['version'],
], $headers),
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_ENCODING => 'gzip,deflate', // 自動解壓
];
curl_setopt_array($ch, array_merge($defaultOpts, $curlOpts));
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
if ($errno) {
error_log("cURL POST $url error [$errno]: $error");
return false;
}
return ['code' => $httpCode, 'body' => $response, 'content_type' => $contentType];
}
// 文件上傳(multipart/form-data)
function postFile(string $url, string $filePath, string $fieldName = 'file', array $extraFields = []) {
$ch = curl_init($url);
$postFields = $extraFields;
$postFields[$fieldName] = new CURLFile($filePath, mime_content_type($filePath), basename($filePath));
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_SSL_VERIFYPEER => true,
]);
return curl_exec($ch);
}
?>
<?php
// composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client([
'base_uri' => 'https://api.example.com/',
'timeout' => 30,
'headers' => ['User-Agent' => 'MyApp/1.0'],
// 'verify' => '/path/to/cacert.pem', // 自定義 CA
]);
try {
// JSON POST
$response = $client->post('orders', [
'json' => [ // 自動設置 Content-Type: application/json + json_encode
'order_id' => 12345,
'items' => [['sku' => 'A001', 'qty' => 2]],
],
]);
$data = json_decode($response->getBody()->getContents(), true);
// 表單 POST
$response = $client->post('notify', [
'form_params' => [ // application/x-www-form-urlencoded
'event' => 'payment_success',
'order_id' => 12345,
],
]);
// 文件上傳
$response = $client->post('upload', [
'multipart' => [
['name' => 'file', 'contents' => fopen('/path/to/file.pdf', 'r'), 'filename' => 'report.pdf'],
['name' => 'folder_id', 'contents' => '123'],
],
]);
// 異步並發請求
$promises = [
'users' => $client->getAsync('users'),
'orders' => $client->getAsync('orders'),
'products'=> $client->getAsync('products'),
];
$results = GuzzleHttp\Promise\Utils::unwrap($promises);
// $results['users']->getBody()...
} catch (RequestException $e) {
$code = $e->getResponse() ? $e->getResponse()->getStatusCode() : 0;
$body = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : $e->getMessage();
error_log("API Error [$code]: $body");
}
?>
| 維度 | Stream Context | cURL | Guzzle |
|---|---|---|---|
| 依賴 | 無(核心) | php-curl 擴展 | Composer 包 |
| 功能豐富度 | 基礎 | 完整 | 極豐富(中間件、異步、重試、認證) |
| 性能 | 良好 | 最佳 | 高(基於 cURL/流) |
| 易用性 | 一般 | 中等(繁瑣) | 極佳(鏈式、PSR-7/18) |
| 並發/異步 | 不支援 | curl_multi(複雜) | 原生 Promise 異步 |
| 測試友好 | 難 Mock | 難 Mock | 易 Mock(HandlerStack) |
| 推薦場景 | 簡單腳本、無 Composer 環境 | 高性能、底層控制、舊項目 | **所有現代項目首選** |
HttpClient 服務類,內部用 Guzzle,對外提供 post()/get()/request(),便於替換實現、加入日誌、監控、熔斷。connect_timeout)與讀取超時(timeout),防止掛死。Idempotency-Key,服務端去重。CURLOPT_SSL_VERIFYPEER => false,配置正確 CA 憑證路徑。現代 PHP 項目**首選 Guzzle**,標準化 PSR-18 Client、PSR-7 Message、異步 Promise、中間件生態,開發效率與可維護性碾壓原生方案。舊項目或極簡場景可用 cURL 封裝;純 CLI 腳本無依賴需求可用 Stream Context。核心原則:**統一封裝、超時控制、錯誤分級、安全傳輸、可觀測性**。