兩種核心方法對比
| 特性 | get_headers() | cURL (curl_getinfo) |
| 實作複雜度 | 極簡(單行) | 需初始化/設定/執行/關閉 |
| 回傳資料 | 完整 Header 陣列 | 可精確取得 HTTP Code、總耗時、DNS 解析時間等 |
| 支援 POST/自定 Header | 需搭配 stream_context | 原生支援 |
| 重導向追蹤 | 預設跟隨,可控制 | 精細控制(CURLOPT_FOLLOWLOCATION、CURLOPT_MAXREDIRS) |
| 超時控制 | stream_context 設定 | CURLOPT_TIMEOUT/CURLOPT_CONNECTTIMEOUT |
| 效能 | 較慢(同步阻塞) | 較快、支援多執行緒 |
| 錯誤處理 | 回傳 false,需 error_get_last() | curl_error()/curl_errno() 明確 |
方案一:get_headers() 快速取得
<?php
/**
* 取得 HTTP 狀態碼(簡易版)
* @param string $url
* @return int|false 狀態碼或 false 失敗
*/
function getHttpStatusSimple(string $url) {
$headers = @get_headers($url, true);
if ($headers === false) return false;
// 陣列第一元素為 "HTTP/1.1 200 OK"
$statusLine = $headers[0] ?? '';
if (preg_match('~HTTP/\d\.\d\s+(\d{3})~', $statusLine, $matches)) {
return (int)$matches[1];
}
return false;
}
// 使用
$status = getHttpStatusSimple('https://example.com');
var_dump($status); // int(200)
// 取得完整 Header 陣列
$headers = get_headers('https://example.com', true);
print_r($headers);
/*
Array
(
[0] => HTTP/1.1 200 OK
[Server] => nginx
[Date] => Mon, 04 Jul 2024 06:21:35 GMT
[Content-Type] => text/html
[Content-Length] => 26898
...
)
*/
?>
方案二:cURL 完整控制版(推薦生產環境)
<?php
/**
* 取得 HTTP 狀態碼與詳細資訊(cURL 版)
* @param string $url
* @param array $options 額外 cURL 選項
* @return array|false ['code'=>int, 'headers'=>array, 'time'=>float, 'error'=>string]
*/
function getHttpStatusCurl(string $url, array $options = []): array|false {
$ch = curl_init();
$defaultOptions = [
CURLOPT_URL => $url,
CURLOPT_HEADER => true, // 回傳 Header
CURLOPT_NOBODY => true, // HEAD 請求,不下載 Body
CURLOPT_RETURNTRANSFER => true, // 字串回傳
CURLOPT_TIMEOUT => 10, // 總超時秒數
CURLOPT_CONNECTTIMEOUT => 5, // 連線超時
CURLOPT_FOLLOWLOCATION => true, // 跟隨重導向
CURLOPT_MAXREDIRS => 5, // 最大重導向次數
CURLOPT_SSL_VERIFYPEER => true, // 驗證 SSL 憑證
CURLOPT_USERAGENT => 'PHP-HTTP-Checker/1.0',
];
curl_setopt_array($ch, $defaultOptions + $options);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($errno) {
return ['code' => 0, 'error' => $error, 'errno' => $errno];
}
// 解析 Header 陣列
$headerSize = $info['header_size'];
$headerStr = substr($response, 0, $headerSize);
$headers = [];
foreach (explode("\r\n", $headerStr) as $line) {
if (strpos($line, ':') !== false) {
[$k, $v] = explode(':', $line, 2);
$headers[trim($k)] = trim($v);
} elseif (preg_match('~^HTTP/\d\.\d\s+(\d{3})~', $line, $m)) {
$headers['_status'] = (int)$m[1];
}
}
return [
'code' => $info['http_code'],
'headers' => $headers,
'time' => $info['total_time'],
'dns' => $info['namelookup_time'],
'connect' => $info['connect_time'],
'ssl' => $info['pretransfer_time'] - $info['connect_time'],
'ttfb' => $info['starttransfer_time'],
];
}
// 使用範例
$result = getHttpStatusCurl('https://api.github.com/users/octocat');
if ($result) {
echo "HTTP {$result['code']} - 耗時 {$result['time']}s\n";
echo "TTFB: {$result['ttfb']}s, DNS: {$result['dns']}s\n";
} else {
echo "請求失敗: {$result['error']}\n";
}
?>
進階應用場景
1. 批次檢測多個 URL(cURL 多執行緒)
<?php
function checkMultiUrls(array $urls, int $concurrency = 10): array {
$mh = curl_multi_init();
$handles = [];
$results = [];
foreach ($urls as $i => $url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => true,
]);
curl_multi_add_handle($mh, $ch);
$handles[$i] = $ch;
}
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh, 0.1);
} while ($running > 0);
foreach ($handles as $i => $ch) {
$info = curl_getinfo($ch);
$results[$urls[$i]] = [
'code' => $info['http_code'],
'time' => $info['total_time'],
'error' => curl_error($ch),
];
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
return $results;
}
?>
2. 健康檢查監控腳本
<?php
$services = [
'API Gateway' => 'https://api.example.com/health',
'Auth Service' => 'https://auth.example.com/ping',
'Database Proxy' => 'https://db-proxy.example.com/status',
];
foreach ($services as $name => $url) {
$result = getHttpStatusCurl($url);
$status = $result && $result['code'] === 200 ? '✅ UP' : '❌ DOWN';
$latency = $result ? "({$result['time']}s)" : '';
echo "[$status] $name $latency\n";
// 整合到監控系統(Prometheus Pushgateway、Datadog、自建 API)
if ($result && $result['code'] !== 200) {
// 發送告警
}
}
?>
常見 HTTP 狀態碼速查
| 分類 | 代碼 | 含義 | 處理建議 |
| 2xx 成功 | 200 | OK | 正常處理 |
| 201 | Created | 資源建立成功 |
| 204 | No Content | 成功無回傳內容 |
| 206 | Partial Content | 範圍請求(斷點續傳) |
| 3xx 重導向 | 301 | Moved Permanently | 更新永久連結 |
| 302 | Found | 暫時重導向 |
| 304 | Not Modified | 快取有效 |
| 4xx 客戶端錯誤 | 400 | Bad Request | 參數驗證失敗 |
| 401 | Unauthorized | 需認證/Token 失效 |
| 403 | Forbidden | 權限不足 |
| 404 | Not Found | 資源不存在 |
| 429 | Too Many Requests | 頻率限制,需退避重試 |
| 5xx 伺服器錯誤 | 500 | Internal Server Error | 記錄錯誤、告警 |
| 502 | Bad Gateway | 上游服務異常 |
| 503 | Service Unavailable | 維護中/過載,Retry-After |
總結
- 簡單檢查存活:
get_headers() 足夠
- 生產環境監控、API 整合、效能分析:cURL 完整版
- 大量並發檢測:curl_multi 非同步批次
- 務必處理超時、重導向循環、SSL 驗證、錯誤碼語意
- 建立統一的 HTTP 客戶端封裝類別,集中管理重試、熔斷、日誌、指標上報