應用場景
- 聚合多個 API 回應(微服務聚合、比價引擎)
- 批量檢查連結有效性、網站監控
- 並發下載、爬蟲加速
- 非阻塞多任務處理
核心類:MultiHttpRequest
<?php
class MultiHttpRequest {
public $urls = array();
public $curlopt_header = 1; // 是否包含回應標頭
public $method = "GET";
function __construct($urls = false) {
$this->urls = $urls;
}
function set_urls($urls) {
$this->urls = $urls;
return $this; // 鏈式調用
}
function is_return_header($b) {
$this->curlopt_header = $b;
return $this;
}
function set_method($m) {
$this->method = strtoupper($m);
return $this;
}
function start() {
if (!is_array($this->urls) || count($this->urls) == 0) {
return false;
}
$curl = array();
$handle = curl_multi_init();
// 建立所有 curl handle
foreach ($this->urls as $k => $v) {
$curl[$k] = $this->add_handle($handle, $v);
}
// 並發執行
$this->exec_handle($handle);
// 收集結果
$results = array();
foreach ($this->urls as $k => $v) {
$content = curl_multi_getcontent($curl[$k]);
$results[$k] = $content;
curl_multi_remove_handle($handle, $curl[$k]);
}
curl_multi_close($handle);
return $results;
}
private function add_handle($handle, $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, $this->curlopt_header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 超時保護
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 測試環境可關閉驗證
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_multi_add_handle($handle, $ch);
return $ch;
}
private function exec_handle($handle) {
$active = null;
// 執行直到無活動 handle
do {
$mrc = curl_multi_exec($handle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
// 等待活動完成
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($handle) != -1) {
do {
$mrc = curl_multi_exec($handle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
}
}
使用範例
<?php
require 'MultiHttpRequest.php';
$urls = array(
"https://api.github.com/users/octocat",
"https://httpbin.org/get",
"https://api.example.com/data",
"https://www.google.com",
);
$mp = new MultiHttpRequest($urls);
$mp->set_method('GET')
->is_return_header(false); // 不需要回應標頭
$results = $mp->start();
foreach ($results as $url => $content) {
echo "=== $url ===\n";
echo strlen($content) . " bytes\n";
// 解析 JSON 等後續處理
// $data = json_decode($content, true);
}
進階擴充:支援 POST、自定義 Header、錯誤處理
<?php
class AdvancedMultiHttpRequest extends MultiHttpRequest {
public $postData = array(); // 各 URL 對應的 POST 資料
public $headers = array(); // 各 URL 對應的自定義 Header
public $options = array(); // 各 URL 額外 curl_setopt 選項
public $callbacks = array(); // 完成回調
protected function add_handle($handle, $url) {
$ch = parent::add_handle($handle, $url);
$key = array_search($url, $this->urls);
if (isset($this->postData[$key])) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postData[$key]);
}
if (isset($this->headers[$key])) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers[$key]);
}
if (isset($this->options[$key])) {
foreach ($this->options[$key] as $opt => $val) {
curl_setopt($ch, $opt, $val);
}
}
return $ch;
}
public function startAsync($callback = null) {
// 非阻塞版本,需搭配 event loop (如 ReactPHP、Swoole)
// 此處略過,生產建議使用 Swoole 或 amphp/http-client
}
}
效能調優參數
| 選項 | 建議值 | 說明 |
| CURLOPT_TIMEOUT | 30 | 最大執行秒數,防止卡死 |
| CURLOPT_CONNECTTIMEOUT | 10 | 連線階段超時 |
| CURLOPT_TCP_KEEPALIVE | 1 | 保持長連線 |
| CURLOPT_FORBID_REUSE | false | 允許連線複用 |
| CURLOPT_MAXCONNECTS | 100 | 連線快取池大小 |
替代方案對比
| 方案 | 優點 | 缺點 | 適用場景 |
| curl_multi (本文) | 無依賴、原生支援、穩定 | 同步阻塞、無協程調度 | 中小併發、傳統 PHP-FPM |
| Guzzle Promise | PSR-7 相容、中介軟體、重試 | 需 Composer、學習曲線 | 現代框架專案 |
| Swoole Coroutine | 真協程、極高併發、毫秒級調度 | 需擴充、學習成本、環境限制 | 高併發微服務、長連線 |
| amphp/http-client | 非阻塞、Promise、無擴充依賴 | 生態較小 | 純 PHP 非阻塞需求 |
常見坑點
curl_multi_select() 返回 -1 時需 usleep(10000) 避免 CPU 100%
- 大量並發(>500)需調整系統
ulimit -n 和 PHP max_execution_time
- HTTPS 目標需正確配置 CA 憑證或關閉驗證(生產必須驗證)
- 記憶體洩漏:循環使用時必須
curl_multi_remove_handle() + curl_close()
- DNS 解析緩存:可啟用
CURLOPT_DNS_CACHE_TIMEOUT
此類庫輕量無依賴,適合快速整合至傳統 PHP 專案解決並發 HTTP 需求。