萬盛學電腦網

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

PHP HTTP 下載類:支援 Header 解析、認證、錯誤處理的完整實現

為什麼不用 file_get_contents?

file_get_contents 無法獲取 HTTP 響應頭 (狀態碼、Content-Type、Set-Cookie 等),無法處理重定向細節、基本認證、超時控制。自定義 Socket 類可完全控制 HTTP 協議細節。

核心類結構

<?php
class HttpDownloader {
    private string $url = '';
    private array $parsed = [];
    private resource $fp = null;
    public string $error = '';
    public string $httpHeader = '';
    public string $html = '';

    // 解析 URL 並初始化屬性
    private function parseUrl(string $url): void {
        $this->url = $url;
        $this->parsed = parse_url($url) + [
            'scheme' => 'http', 'host' => '', 'port' => 80,
            'user' => '', 'pass' => '', 'path' => '/', 'query' => ''
        ];
        if ($this->parsed['query']) $this->parsed['path'] .= '?' . $this->parsed['query'];
    }

    // 建立 Socket 連接並發送請求
    public function open(string $url): bool {
        $this->parseUrl($url);
        $host = $this->parsed['host'];
        $port = $this->parsed['port'];
        $timeout = 30;

        $this->fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
        if (!$this->fp) {
            $this->error = "連接失敗 ($errno): $errstr";
            return false;
        }
        stream_set_timeout($this->fp, $timeout);

        // 構建請求頭
        $request = "GET {$this->parsed['path']} HTTP/1.1\r\n";
        $request .= "Host: $host\r\n";
        $request .= "User-Agent: PHP HttpDownloader/1.0\r\n";
        $request .= "Connection: Close\r\n";
        if ($this->parsed['user']) {
            $auth = base64_encode("{$this->parsed['user']}:{$this->parsed['pass']}");
            $request .= "Authorization: Basic $auth\r\n";
        }
        $request .= "\r\n";

        fwrite($this->fp, $request);
        return $this->readResponse();
    }

    // 讀取並分離 Header / Body
    private function readResponse(): bool {
        $header = '';
        while (!feof($this->fp)) {
            $line = fgets($this->fp, 4096);
            $header .= $line;
            if ($line === "\r\n" || $line === "\n") break;
        }
        $this->httpHeader = $header;

        // 簡易解析狀態碼
        if (preg_match('/HTTP\/\d\.\d\s+(\d{3})/', $header, $m)) {
            $code = (int)$m[1];
            if ($code >= 400) {
                $this->error = "HTTP $code";
                // 仍繼續讀取 body 以便調試
            }
        }

        $this->html = stream_get_contents($this->fp);
        fclose($this->fp);
        return true;
    }

    // 獲取指定響應頭
    public function getHeader(string $name): ?string {
        $pattern = '/^' . preg_quote($name, '/') . ':\s*(.+)$/mi';
        return preg_match($pattern, $this->httpHeader, $m) ? trim($m[1]) : null;
    }
}

// 使用示例
$downloader = new HttpDownloader();
if ($downloader->open('https://example.com/api/data')) {
    echo "Status: " . $downloader->getHeader('Status') . "<br>";
    echo "Content-Type: " . $downloader->getHeader('Content-Type') . "<br>";
    echo "Body length: " . strlen($downloader->html) . "<br>";
    // 處理 $downloader->html ...
} else {
    echo "Error: " . $downloader->error;
}
?>

生產環境建議

  • 改用 cURL (curl_exec):功能更全、性能更好、支援 HTTPS/HTTP2/多路復用。
  • 或使用 Guzzle / Symfony HttpClient 等高級 HTTP 客戶端庫 (Composer 安裝),提供中間件、重試、異步、PSR-18 標準介面。
  • 本類僅作為教學演示 Socket 底層原理。
copyright © 萬盛學電腦網 all rights reserved