cURL 是 PHP 進行網絡請求的瑞士軍刀。本文提供一個生產級的初始化模板,涵蓋 GET/POST、Cookie 管理、Header 定制、超時控制、重定向追蹤、SSL 設定、代理支援等常見場景,並附上詳細註解。
function curlRequest(string $url, array $options = []): string {
$ch = curl_init();
// === 通用基礎配置 ===
$defaults = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true, // 返回字符串而非直接輸出
CURLOPT_HEADER => false, // 不包含回應 Header
CURLOPT_FOLLOWLOCATION => true, // 自動追蹤 301/302
CURLOPT_MAXREDIRS => 10, // 最大重定向次數
CURLOPT_CONNECTTIMEOUT => 10, // 連接超時(秒)
CURLOPT_TIMEOUT => 30, // 總執行超時(秒)
CURLOPT_SSL_VERIFYPEER => true, // 驗證 SSL 憑證(生產必開)
CURLOPT_SSL_VERIFYHOST => 2, // 驗證 Hostname
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP-cURL/' . phpversion() . ')',
CURLOPT_ENCODING => 'gzip, deflate', // 自動解壓
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, // 強制 IPv4,避免 DNS 卡頓
];
// === 合併用戶自定義選項 ===
curl_setopt_array($ch, $defaults + $options);
// === 執行與錯誤處理 ===
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($errno) {
throw new RuntimeException("cURL 錯誤 [$errno]: $error (URL: $url)");
}
// 可選:檢查 HTTP 狀態碼
if ($info['http_code'] >= 400) {
throw new RuntimeException("HTTP {$info['http_code']}: $url");
}
return $response;
}
// 表單
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = http_build_query(['key' => 'value']);
// JSON API
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = json_encode(['key' => 'value']);
$options[CURLOPT_HTTPHEADER] = ['Content-Type: application/json', 'Accept: application/json'];
$cookieFile = sys_get_temp_dir() . '/cookie_' . md5($domain) . '.txt';
$options[CURLOPT_COOKIEJAR] = $cookieFile; // 寫入
$options[CURLOPT_COOKIEFILE] = $cookieFile; // 讀取
$options[CURLOPT_HTTPHEADER] = [
'Referer: https://example.com/',
'Origin: https://example.com',
'X-Requested-With: XMLHttpRequest',
];
$options[CURLOPT_REFERER] = 'https://example.com/';
$options[CURLOPT_PROXY] = 'https://proxy.example.com:3128';
$options[CURLOPT_PROXYUSERPWD] = 'user:pass';
$options[CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2; // 強制 TLS 1.2+
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = [
'file' => new CURLFile('/path/to/file.jpg', 'image/jpeg', 'filename.jpg'),
'field' => 'value',
];
使用 curl_multi_* 系列函數可實現並發,大幅降低批量請求總耗時。簡易封裝:
function curlMultiRequest(array $urls, array $commonOptions = []): array {
$mh = curl_multi_init();
$handles = [];
foreach ($urls as $i => $url) {
$ch = curl_init();
curl_setopt_array($ch, $commonOptions + [CURLOPT_URL => $url]);
curl_multi_add_handle($mh, $ch);
$handles[$i] = $ch;
}
$running = null;
do { curl_multi_exec($mh, $running); } while ($running > 0);
$results = [];
foreach ($handles as $i => $ch) {
$results[$i] = curl_multi_getcontent($ch);
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
return $results;
}
CURLOPT_VERBOSE => true + CURLOPT_STDERR => fopen('php://temp', 'w+') 可捕獲詳細通訊日誌。curl_getinfo($ch, CURLINFO_HEADER_OUT) 查看實際發送的請求 Header。curl_error()、curl_errno()、curl_getinfo() 定位問題。掌握 cURL 核心選項與錯誤處理模式,即可應對 90% 的 HTTP 交互場景。建議將上述模板封裝為專案共用的 Service 類,統一超時、重試、日誌、監控策略。