萬盛學電腦網

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

PHP HTTP Client 類封裝:原生流上下文實現 GET/POST、Header、Cookie、Referer 全支持

設計目標

  • **零依賴**:僅使用 PHP 內置 stream_context + file_get_contents,無需 cURL 擴展、無需 Guzzle
  • **輕量級**:單文件、單類、< 100 行核心代碼
  • **功能完整**:GET/POST、自定義 Header、Cookie、Referer、User-Agent、超時、代理、HTTPS 驗證控制
  • **調試友好**:保存請求/響應 Header、原始 Body,便於排查

核心類實現

<?php
/**
 * 輕量級 HTTP Client
 * 基於 PHP Stream Context,無外部依賴
 */
class HttpClient
{
    public ?string $buffer = null;      // 響應 Body
    public ?string $requestHeaders = null;  // 發送的請求 Header
    public ?string $responseHeaders = null; // 接收的響應 Header
    public ?string $referer = null;     // 自定義 Referer
    
    private array $options = [];        // 全局默認選項
    private resource|null $context = null;

    public static function create(array $options = []): self
    {
        return new self($options);
    }

    private function __construct(array $options = [])
    {
        $this->options = array_merge([
            'timeout' => 30,
            'user_agent' => 'PHP-HttpClient/1.0 (+https://example.com)',
            'verify_ssl' => true,       // 生產環境建議 true
            'follow_location' => true,
            'max_redirects' => 5,
            'proxy' => null,            // 'tcp://proxy:8080'
        ], $options);
    }

    /** 發送 GET 請求 */
    public function get(string $url, array $query = [], ?string $cookie = null): string|false
    {
        if ($query) {
            $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($query);
        }
        return $this->request('GET', $url, null, $cookie);
    }

    /** 發送 POST 請求 */
    public function post(string $url, array|string $data = [], ?string $cookie = null): string|false
    {
        $body = is_array($data) ? http_build_query($data) : $data;
        return $this->request('POST', $url, $body, $cookie);
    }

    /** 通用請求方法 */
    public function request(string $method, string $url, ?string $body, ?string $cookie): string|false
    {
        $parsed = parse_url($url);
        if (!$parsed) return $this->setError("Invalid URL: $url");

        $host = $parsed['host'];
        $headers = [
            "Host: $host",
            "Connection: close",
            "Accept: */*",
            "User-Agent: {$this->options['user_agent']}",
            "DNT: 1", // Do Not Track
        ];

        if ($cookie) $headers[] = "Cookie: $cookie";
        if ($this->referer) $headers[] = "Referer: {$this->referer}";
        if ($method === 'POST' && $body !== null) {
            $headers[] = "Content-Type: application/x-www-form-urlencoded";
            $headers[] = "Content-Length: " . strlen($body);
        }

        $contextOptions = [
            'http' => [
                'method' => $method,
                'header' => implode("\r\n", $headers),
                'timeout' => $this->options['timeout'],
                'follow_location' => $this->options['follow_location'],
                'max_redirects' => $this->options['max_redirects'],
                'ignore_errors' => true, // 我們手動處理錯誤碼
            ],
            'ssl' => [
                'verify_peer' => $this->options['verify_ssl'],
                'verify_peer_name' => $this->options['verify_ssl'],
            ],
        ];

        if ($this->options['proxy']) {
            $contextOptions['http']['proxy'] = $this->options['proxy'];
            $contextOptions['http']['request_fulluri'] = true;
        }

        if ($body !== null) {
            $contextOptions['http']['content'] = $body;
        }

        $this->context = stream_context_create($contextOptions);
        $this->requestHeaders = implode("\r\n", $headers);

        // 發送請求
        $this->buffer = @file_get_contents($url, false, $this->context);
        
        // 獲取響應 Header (從 $http_response_header 全局變量)
        $this->responseHeaders = implode("\r\n", $http_response_header ?? []);

        return $this->buffer;
    }

    /** 獲取響應狀態碼 */
    public function getStatusCode(): int
    {
        if (!$this->responseHeaders) return 0;
        $firstLine = explode("\n", $this->responseHeaders)[0] ?? '';
        if (preg_match('/HTTP\/\d\.\d\s+(\d{3})/', $firstLine, $m)) {
            return (int)$m[1];
        }
        return 0;
    }

    /** 判斷請求是否成功 (2xx) */
    public function isSuccess(): bool
    {
        $code = $this->getStatusCode();
        return $code >= 200 && $code < 300;
    }

    /** 獲取響應 Header 陣列 */
    public function getResponseHeaders(): array
    {
        $headers = [];
        foreach (($http_response_header ?? []) as $h) {
            if (strpos($h, ':') !== false) {
                [$k, $v] = explode(':', $h, 2);
                $headers[strtolower(trim($k))] = trim($v);
            }
        }
        return $headers;
    }

    private function setError(string $msg): false
    {
        $this->buffer = $msg;
        return false;
    }
}

使用示例

基礎 GET/POST

$client = HttpClient::create(['timeout' => 10, 'verify_ssl' => false]);

// GET 帶查詢參數
$html = $client->get('https://httpbin.org/get', ['page' => 1, 'size' => 20]);
echo "Status: " . $client->getStatusCode() . "\n";
echo "Body: " . $client->buffer . "\n";

// POST 表單
$result = $client->post('https://httpbin.org/post', [
    'username' => 'test',
    'password' => '123456',
]);
echo $result;

// 檢查請求/響應 Header (調試用)
echo "Request Headers:\n" . $client->requestHeaders . "\n\n";
echo "Response Headers:\n" . $client->responseHeaders . "\n";

攜帶 Cookie / Referer / 自定義 Header

$client = HttpClient::create();
$client->referer = 'https://example.com/dashboard';

// 登錄獲取 Cookie
$client->post('https://site.com/login', ['user' => 'a', 'pwd' => 'b']);
$cookies = [];
foreach ($client->getResponseHeaders() as $k => $v) {
    if (str_starts_with($k, 'set-cookie')) {
        $cookies[] = explode(';', $v)[0]; // 取 name=value 部分
    }
}
$cookieStr = implode('; ', $cookies);

// 後續請求攜帶 Cookie
$client->get('https://site.com/profile', [], $cookieStr);

文件上傳 (multipart/form-data)

// 擴展:支援文件上傳
public function postMultipart(string $url, array $fields, array $files, ?string $cookie = null): string|false
{
    $boundary = '----HttpClientBoundary' . microtime(true);
    $body = '';
    
    // 普通字段
    foreach ($fields as $name => $value) {
        $body .= "--$boundary\r\n";
        $body .= "Content-Disposition: form-data; name=\"$name\"\r\n\r\n";
        $body .= "$value\r\n";
    }
    // 文件字段
    foreach ($files as $name => $path) {
        $content = file_get_contents($path);
        $filename = basename($path);
        $mime = mime_content_type($path) ?: 'application/octet-stream';
        $body .= "--$boundary\r\n";
        $body .= "Content-Disposition: form-data; name=\"$name\"; filename=\"$filename\"\r\n";
        $body .= "Content-Type: $mime\r\n\r\n";
        $body .= "$content\r\n";
    }
    $body .= "--$boundary--\r\n";

    $headers = [
        "Content-Type: multipart/form-data; boundary=$boundary",
        "Content-Length: " . strlen($body),
    ];
    // ... 合並到 contextOptions['http']['header'] ...
    // 同 request() 邏輯
}

對比:為什麼不直接用 cURL / Guzzle?

方案優點缺點適用場景
本類 (Stream)零依賴、標準庫、部署極簡、PHAR 打包友好無連接池、無異步、無自動重試、HTTP/2 不支援CLI 腳本、Serverless、輕量容器、遷移舊項目
cURL 擴展功能全、性能高、支援 HTTP/2、連接復用、證書管理需安裝擴展、API 較繁瑣高併發、長連接、複雜 TLS 需求
Guzzle / Symfony HttpClientPSR-18 標準、中間件、異步、重試、測試雙工Composer 依賴、體積大、學習曲線現代框架專案 (Laravel/Symfony/API Platform)

生產環境增強建議

  1. 超時精細控制:連接超時 vs 讀取超時 (stream_context_set_option)
  2. 自動重試:指數退避 + 抖動 (Guzzle Middleware / 自寫裝飾器)
  3. 熔斷器:連續失敗快速失效,防止雪崩
  4. 指標監控:請求延遲、錯誤率、QPS (Prometheus + Grafana)
  5. 證書釘裹:高安全場景驗證公鑰指紋

總結

HttpClient 類演示了 PHP **Stream Context** 的強大能力:無需任何擴展即可實現完整 HTTP 客戶端功能。對於 CLI 工具、Serverless 函數、極簡部署環境,它是 **Guzzle 的零依賴替代品**。生產級高併發服務建議遷移至 Guzzle/Symfony HttpClient 或 Swoole 協程客戶端,獲得連接池、異步、HTTP/2 等高級特性。

copyright © 萬盛學電腦網 all rights reserved