cURL 是 PHP 與外部 HTTP 服務交互的標準利器:抓取網頁、調用 API、文件上傳下載、模擬登錄、Webhook 回調。本文從底層原理到高級用法,構建一個可生產使用的 HttpClient 封裝,涵蓋並發請求、重試熔斷、中間件、異步非阻塞等進階模式。
基礎四步驟
<?php
// 1. 初始化
$ch = curl_init();
// 2. 設置選項 (核心)
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.example.com/users',
CURLOPT_RETURNTRANSFER => true, // 返回字符串而非直接輸出
CURLOPT_HEADER => false, // 不包含響應頭
CURLOPT_FOLLOWLOCATION => true, // 跟隨重定向
CURLOPT_MAXREDIRS => 5, // 最大重定向次數
CURLOPT_TIMEOUT => 10, // 總超時秒數
CURLOPT_CONNECTTIMEOUT => 3, // 連接超時
CURLOPT_SSL_VERIFYPEER => true, // 驗證 SSL 證書 (生產必須 true)
CURLOPT_SSL_VERIFYHOST => 2, // 驗證域名匹配
CURLOPT_USERAGENT => 'MyApp/1.0', // 自定義 UA
CURLOPT_HTTPHEADER => [ // 自定義頭
'Accept: application/json',
'Authorization: Bearer ' . $token,
],
]);
// 3. 執行
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
// 4. 關閉
curl_close($ch);
if ($errno) {
throw new \RuntimeException("cURL error ($errno): $error");
}
// 處理 $response...
?>
核心選項分類速查
| 類別 | 關鍵選項 | 說明 |
| 請求行/頭 | CURLOPT_URL | 請求 URL |
CURLOPT_CUSTOMREQUEST | HTTP 方法 (GET/POST/PUT/PATCH/DELETE) |
CURLOPT_HTTPHEADER | 陣列格式:['Header: value', ...] |
CURLOPT_USERAGENT | User-Agent 字符串 |
| 請求體 | CURLOPT_POST | true 發送 POST |
CURLOPT_POSTFIELDS | 數據:陣列 (multipart/form-data) 或字符串 (application/x-www-form-urlencoded/json) |
CURLOPT_READFUNCTION | 流式讀取大文件上傳回調 |
CURLOPT_INFILESIZE | 上傳文件大小 (配合 READFUNCTION) |
CURLOPT_HTTPPOST | 已棄用,用 POSTFIELDS + CURLFile |
| 響應處理 | CURLOPT_RETURNTRANSFER | true 返回字符串,false 直接輸出 |
CURLOPT_HEADER | true 包含響應頭 |
CURLOPT_WRITEFUNCTION | 流式寫入響應體回調 (大文件下載) |
CURLOPT_HEADERFUNCTION | 解析響應頭回調 |
| SSL/TLS | CURLOPT_SSL_VERIFYPEER | 生產必須 true,開發可 false |
CURLOPT_CAINFO | 自定義 CA 憑證包路徑 |
CURLOPT_SSLCERT/SSLKEY | 客戶端憑證雙向認證 |
CURLOPT_SSL_CIPHER_LIST | 指定加密套件 |
| 超時/限制 | CURLOPT_TIMEOUT | 整個請求最大秒數 |
CURLOPT_CONNECTTIMEOUT | 建立連接最大秒數 |
CURLOPT_MAXFILESIZE | 最大下載位元組數 |
| 並發/複用 | curl_multi_* 系列 | 並發多請求 |
CURLOPT_PIPEWAIT | 管道等待 |
CURLOPT_TCP_KEEPALIVE | TCP 保活 |
進階實戰封裝:HttpClient 類
<?php
class HttpClient {
private array $defaultOptions = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_ENCODING => 'gzip, deflate', // 自動解壓
CURLOPT_USERAGENT => 'MyApp/2.0 (+https://example.com)',
];
private array $middlewares = []; // 中間件:請求/響應攔截
public function __construct(array $defaultOptions = []) {
$this->defaultOptions = array_merge($this->defaultOptions, $defaultOptions);
}
public function addMiddleware(callable $middleware): self {
$this->middlewares[] = $middleware;
return $this;
}
public function request(string $method, string $url, array $options = []): Response {
$ch = curl_init();
$mergedOptions = array_merge($this->defaultOptions, $options, [
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => strtoupper($method),
]);
// 應用請求中間件
foreach ($this->middlewares as $mw) {
$mergedOptions = $mw($mergedOptions, 'request') ?? $mergedOptions;
}
curl_setopt_array($ch, $mergedOptions);
$body = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$response = new Response($body, $info, $errno, $error);
// 應用響應中間件
foreach ($this->middlewares as $mw) {
$response = $mw($response, 'response') ?? $response;
}
if ($errno) {
throw new HttpException($error, $errno, $response);
}
return $response;
}
// 便捷方法
public function get(string $url, array $options = []): Response { return $this->request('GET', $url, $options); }
public function post(string $url, array $data = [], array $options = []): Response {
return $this->request('POST', $url, array_merge($options, [CURLOPT_POSTFIELDS => $data]));
}
public function postJson(string $url, array $data, array $options = []): Response {
return $this->request('POST', $url, array_merge($options, [
CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
]));
}
}
class Response {
public string $body;
public array $info;
public int $errno;
public string $error;
public int $statusCode;
public array $headers = [];
public function __construct(string $body, array $info, int $errno, string $error) {
$this->body = $body;
$this->info = $info;
$this->errno = $errno;
$this->error = $error;
$this->statusCode = $info['http_code'] ?? 0;
$this->parseHeaders($info['header'] ?? '');
}
private function parseHeaders(string $headerStr): void {
foreach (explode("\r\n", $headerStr) as $line) {
if (strpos($line, ':') !== false) {
[$k, $v] = explode(':', $line, 2);
$this->headers[trim($k)] = trim($v);
}
}
}
public function json(): array|object|null {
return json_decode($this->body, true);
}
public function isSuccess(): bool {
return $this->errno === 0 && $this->statusCode >= 200 && $this->statusCode < 300;
}
}
class HttpException extends \Exception {
public Response $response;
public function __construct(string $message, int $code, Response $response) {
parent::__construct($message, $code);
$this->response = $response;
}
}
?>
中間件模式:橫切關注點分離
<?php
// 1. 日誌中間件
$client->addMiddleware(function($options, $phase) {
if ($phase === 'request') {
error_log("[HTTP] {$options[CURLOPT_CUSTOMREQUEST]} {$options[CURLOPT_URL]}");
return $options;
}
if ($phase === 'response') {
error_log("[HTTP] Response: {$options->statusCode} " . strlen($options->body) . " bytes");
}
});
// 2. 重試中間件 (指數退避)
$client->addMiddleware(function($options, $phase) use ($client) {
if ($phase !== 'response') return $options;
$maxRetries = 3;
$retryableCodes = [429, 500, 502, 503, 504];
for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
if (!in_array($options->statusCode, $retryableCodes)) break;
if ($attempt === $maxRetries) break;
$delay = (int)($options->headers['Retry-After'] ?? pow(2, $attempt) * 100000); // 微秒
usleep($delay);
// 重新發送原請求 (需保存原請求參數,此處簡化)
// 實際需在請求階段記錄原始選項
}
return $options;
});
// 3. 熔斷器中間件 (簡化版)
$failureCount = 0;
$client->addMiddleware(function($options, $phase) use (&$failureCount) {
if ($phase === 'response') {
if ($options->isSuccess()) $failureCount = 0;
else $failureCount++;
if ($failureCount >= 5) {
// 觸發熔斷:拋出異常、快速失敗、告警
throw new \RuntimeException('Circuit breaker open');
}
}
});
?>
並發請求:curl_multi 批量處理
<?php
function multiRequest(array $urls, int $maxConcurrent = 10): array {
$mh = curl_multi_init();
$handles = [];
$results = [];
$queue = $urls;
$active = 0;
// 初始添加
while ($active < $maxConcurrent && $queue) {
$url = array_shift($queue);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
curl_multi_add_handle($mh, $ch);
$handles[(int)$ch] = $url;
$active++;
}
do {
$status = curl_multi_exec($mh, $running);
if ($status !== CURLM_OK) break;
// 等待活動
curl_multi_select($mh, 0.1);
// 處理完成的
while ($done = curl_multi_info_read($mh)) {
$ch = $done['handle'];
$url = $handles[(int)$ch];
$result = curl_multi_getcontent($ch);
$info = curl_getinfo($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$results[$url] = compact('result', 'info', 'errno', 'error');
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
$active--;
// 補充新請求
if ($queue) {
$url = array_shift($queue);
$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10]);
curl_multi_add_handle($mh, $ch);
$handles[(int)$ch] = $url;
$active++;
}
}
} while ($running > 0);
curl_multi_cleanup($mh);
return $results;
}
// 使用
$urls = array_fill(0, 50, 'https://httpbin.org/delay/1');
$results = multiRequest($urls, 20); // 20 並發,總耗時 ≈ 3s (vs 串行 50s)
?>
文件上傳與下載
上傳 (multipart/form-data)
<?php
$filePath = '/path/to/image.png';
$cfile = new CURLFile($filePath, 'image/png', 'avatar.png'); // PHP 5.5+
// 老版本:'@' . $filePath . ';type=image/png;filename=avatar.png'
$ch = curl_init('https://api.example.com/upload');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'file' => $cfile,
'user_id' => 123,
],
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
?>
大文件流式下載 (不佔用 PHP 內存)
<?php
$url = 'https://example.com/large-file.zip';
$savePath = '/data/downloads/large-file.zip';
$ch = curl_init($url);
$fp = fopen($savePath, 'wb');
curl_setopt_array($ch, [
CURLOPT_FILE => $fp, // 直接寫入文件句柄
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 0, // 無總超時
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_NOPROGRESS => false, // 開啟進度回調
CURLOPT_PROGRESSFUNCTION => function($ch, $dlTotal, $dlNow, $ulTotal, $ulNow) {
if ($dlTotal > 0) {
printf("\rDownloaded: %.2f%% (%d/%d bytes)", $dlNow/$dlTotal*100, $dlNow, $dlTotal);
}
},
]);
curl_exec($ch);
curl_close($ch);
fclose($fp);
echo "\nDownload complete.\n";
?>
常見坑點與避雷
| 坑點 | 現象 | 解決 |
| SSL 證書驗證失敗 | cURL error 60: SSL certificate problem | 設置 CURLOPT_CAINFO 指向有效 CA 憑證包 (cacert.pem),絕不關閉驗證 |
| POST 數據格式錯誤 | 服務端收到空數組 | 傳 JSON 時:CURLOPT_POSTFIELDS => json_encode($data) + Content-Type: application/json;傳表單:直接傳陣列 |
| 超時設置無效 | 請求掛起超過設置時間 | 檢查 CURLOPT_NOSIGNAL => 1 (多線程環境),確保 DNS 解析快 |
| 重定向丟失 Cookie | 登入後跳轉失效 | CURLOPT_COOKIEJAR/COOKIEFILE 設置 Cookie 文件,或手動處理 Set-Cookie 頭 |
| 大響應體 OOM | memory_limit 耗盡 | 用 CURLOPT_WRITEFUNCTION 流式寫入文件/壓縮流 |
| 並發過高導致連接耗盡 | Too many open files / TIME_WAIT 堆積 | 限制並發數、啟用 HTTP/2 多路複用、調整內核參數 |
現代替代方案
- GuzzleHttp:功能最全、中間件生態豐富、PSR-7/18 標準、異步 Promise 支援,企業級首選。
- Symfony HttpClient:零依賴 (僅需 cURL 擴展)、自動解碼、重試、範圍請求、Scoping Client。
- Swoole\Coroutine\Http\Client:協程非阻塞、極高並發、配合 Swoole 框架使用。
- PHP 8.1+
curl 類:面向對象封裝,$ch = curl_init(); $ch->setOpt(...); $ch->exec();。