萬盛學電腦網

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

PHP底層HTTP請求實現:基於fsockopen的httpRequest函數解析與現代替代

早期PHP無cURL擴展時,開發者常用fsockopen手工構造HTTP報文。本文解析一個經典的httpRequest函數實現,指出其局限,並推薦現代替代方案(cURL、Guzzle、Http\Client)。

經典httpRequest函數解析

function httpRequest(
    string $url,
    $post = '',
    string $method = 'GET',
    int $limit = 0,
    bool $returnHeader = false,
    string $cookie = '',
    bool $bysocket = false,
    string $ip = '',
    int $timeout = 15,
    bool $block = true
): string|array|false {
    $matches = parse_url($url);
    $host = $matches['host'] ?? '';
    $path = ($matches['path'] ?? '/') . ($matches['query'] ? '?' . $matches['query'] : '');
    $port = $matches['port'] ?? 80;
    $out = '';
    if (strtoupper($method) === 'POST') {
        $post = is_array($post) ? http_build_query($post) : $post;
        $out = "POST $path HTTP/1.0\r\n";
        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out .= "Content-Length: " . strlen($post) . "\r\n";
    } else {
        $out = "GET $path HTTP/1.0\r\n";
    }
    $out .= "Host: $host\r\n";
    $out .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";
    $out .= "Connection: Close\r\n";
    if ($cookie) $out .= "Cookie: $cookie\r\n";
    $out .= "\r\n";
    if ($post) $out .= $post;
    $fp = fsockopen($ip ?: $host, $port, $errno, $errstr, $timeout);
    if (!$fp) return false;
    stream_set_blocking($fp, $block);
    stream_set_timeout($fp, $timeout);
    fwrite($fp, $out);
    $header = $content = '';
    $headerDone = false;
    while (!feof($fp)) {
        $line = fgets($fp);
        if (!$headerDone) {
            $header .= $line;
            if ($line === "\r\n" || $line === "\n") $headerDone = true;
        } else {
            $content .= $line;
            if ($limit && strlen($content) >= $limit) break;
        }
    }
    fclose($fp);
    return $returnHeader ? [$header, $content] : $content;
}

主要局限

  • 不支持HTTPS:需改用ssl://或tls://協議前綴並驗證證書,極其繁瑣。
  • 無自動重定向:需手動解析Location頭並遞歸請求。
  • 無壓縮解碼:需手動處理gzip/deflate。
  • 無連接池/Keep-Alive:每次請求新建TCP連接,性能差。
  • 錯誤處理脆弱:無重試、熔斷、超時細粒度控制。

現代替代方案對比

Guzzle快速上手

composer require guzzlehttp/guzzle
$client = new \GuzzleHttp\Client(['timeout' => 10, 'verify' => '/path/to/cacert.pem']);
$response = $client->post('https://api.example.com/users', [
    'json' => ['name' => 'test'],
    'headers' => ['Authorization' => 'Bearer token'],
]);
$data = json_decode($response->getBody()->getContents(), true);

除非極度受限環境(無cURL、無Composer),**強烈建議遷移至現代HTTP客戶端庫**,專注業務邏輯而非造輪子。

copyright © 萬盛學電腦網 all rights reserved
方案優點缺點適用場景
cURL擴展功能全、性能高、原生支持HTTPS/HTTP2/代理/並發API較底層、易誤用所有HTTP客戶端需求
GuzzlePSR-18/17兼容、中間件、異步、重試、測試友好依賴較多、學習曲線現代框架項目、微服務調用
Symfony HttpClient零配置、自動解碼、異步、Scoping Client需Symfony組件Symfony/Laravel項目
ext-http (pecl_http)C層實現、高性能、完整HTTP/2需編譯擴展、部署複雜極高性能場景