萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實作帶超時功能的 get_headers 替代方案

前言

PHP 內建 get_headers() 不支援超時設定,遇到回應緩慢或無回應的伺服器會導致腳本卡死。本文提供基於 cURL 的替代方案,支援精確超時控制、重導向追蹤、錯誤處理。

核心函式:get_url_headers()

<?php
/**
 * 取得 HTTP 回應標頭 (支援超時)
 *
 * @param string $url      目標 URL
 * @param int    $timeout  總超時秒數
 * @param int    $connectTimeout 連線超時秒數
 * @return array|false     關聯陣列 [標頭名 => 值],第一個元素索引 0 為狀態行
 */
function get_url_headers(string $url, int $timeout = 10, int $connectTimeout = 5)
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_HEADER => true,           // 輸出標頭
        CURLOPT_NOBODY => true,           // HEAD 請求 (不下載內文)
        CURLOPT_RETURNTRANSFER => true,   // 回傳字串
        CURLOPT_TIMEOUT => $timeout,      // 總超時
        CURLOPT_CONNECTTIMEOUT => $connectTimeout, // 連線超時
        CURLOPT_FOLLOWLOCATION => true,   // 跟隨重導向
        CURLOPT_MAXREDIRS => 10,          // 最大重導向次數
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP HeaderChecker/1.0)',
        CURLOPT_SSL_VERIFYPEER => true,   // 生產環境建議 true
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);

    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    if ($errno) {
        // 可選:拋出例外或記錄日誌
        return false;
    }

    // 解析標頭
    $headerText = substr($response, 0, $info['header_size']);
    $headers = [];
    $lines = explode("\n", $headerText);

    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') continue;

        // 狀態行: HTTP/1.1 200 OK
        if (preg_match('/^HTTP\/\d\.\d\s+(\d{3})/', $line, $m)) {
            $headers[0] = $line; // 保留原始狀態行
            $headers['http_code'] = (int)$m[1];
            continue;
        }

        // 一般標頭: Name: value
        if (strpos($line, ':') !== false) {
            [$name, $value] = explode(':', $line, 2);
            $name = trim($name);
            $value = trim($value);
            // 標頭可能重複 (如 Set-Cookie),轉為陣列
            if (isset($headers[$name])) {
                if (!is_array($headers[$name])) {
                    $headers[$name] = [$headers[$name]];
                }
                $headers[$name][] = $value;
            } else {
                $headers[$name] = $value;
            }
        }
    }

    return $headers;
}

// 使用範例
$headers = get_url_headers('https://httpbin.org/headers', 5);
if ($headers) {
    echo "HTTP 狀態: {$headers['http_code']}\n";
    echo "Content-Type: " . ($headers['Content-Type'] ?? 'N/A') . "\n";
    echo "Server: " . ($headers['Server'] ?? 'N/A') . "\n";
    print_r($headers);
} else {
    echo "請求失敗或超時";
}
?>

進階:支援並發請求 (curl_multi)

function get_multi_url_headers(array $urls, int $timeout = 10): array
{
    $mh = curl_multi_init();
    $handles = [];

    foreach ($urls as $i => $url) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_HEADER => true,
            CURLOPT_NOBODY => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_USERAGENT => 'PHP MultiHeaderChecker/1.0',
        ]);
        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);

    $results = [];
    foreach ($handles as $i => $ch) {
        $info = curl_getinfo($ch);
        $response = curl_multi_getcontent($ch);
        $errno = curl_errno($ch);
        $results[$i] = [
            'url' => $urls[$i],
            'http_code' => $info['http_code'],
            'headers' => $errno ? null : parse_headers($response, $info['header_size']),
            'error' => $errno ? curl_error($ch) : null,
        ];
        curl_multi_remove_handle($mh, $ch);
    }
    curl_multi_close($mh);
    return $results;
}

function parse_headers($response, $headerSize)
{
    // 同單一版本解析邏輯...
}
?>

比較:原生 get_headers vs cURL 版

特性get_headers()cURL 版
超時控制無 (受 default_socket_timeout 影響)精確控制 (總/連線)
重導向自動跟隨 (無上限控制)可控制 MAXREDIRS
SSL 驗證依 php.ini openssl 設定可精細控制
User-Agentphp.ini user_agent 或預設可自訂
效能 (單請求)略快 (內建)略慢 (進程開銷)
並發支援無curl_multi 完美支援
錯誤處理警告 + 回傳 false詳細錯誤碼/訊息

總結

生產環境檢查遠端資源標頭時,請使用 cURL 版本,確保可控超時、避免阻塞。批量檢查時善用 curl_multi 大幅提升效率。

copyright © 萬盛學電腦網 all rights reserved