萬盛學電腦網

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

PHP fsockopen 模擬 HTTP 請求:GET/POST 完整實現

原理概述

使用 fsockopen() 建立 TCP 連接,手動構造 HTTP 協議報文,實現無依賴的 HTTP 客戶端。適合無 cURL、Guzzle 環境,或需精細控制協議細節場景。

基礎 GET 請求實現

<?php
function httpGet(string $host, string $path = '/', int $port = 80, int $timeout = 30): ?string {
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);
    if (!$fp) {
        throw new RuntimeException("連接失敗 [$errno]: $errstr");
    }
    
    // 構造 HTTP/1.1 請求報文
    $request = "GET $path HTTP/1.1\r\n";
    $request .= "Host: $host\r\n";
    $request .= "User-Agent: PHP-fsockopen/1.0\r\n";
    $request .= "Accept: */*\r\n";
    $request .= "Connection: Close\r\n"; // 短連接,避免保持連接導致讀取阻塞
    $request .= "\r\n";
    
    fwrite($fp, $request);
    
    // 讀取響應
    $response = '';
    while (!feof($fp)) {
        $response .= fgets($fp, 4096);
    }
    fclose($fp);
    
    // 簡易分離頭部和主體
    list($headers, $body) = explode("\r\n\r\n", $response, 2);
    return $body;
}

// 使用
try {
    $html = httpGet('www.example.com', '/');
    file_put_contents('example.html', $html);
    echo "下載完成,大小: " . strlen($html) . " 字節";
} catch (Exception $e) {
    echo "錯誤: " . $e->getMessage();
}
?>

POST 請求實現

<?php
function httpPost(string $host, string $path, array $data, int $port = 80, int $timeout = 30): ?string {
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);
    if (!$fp) throw new RuntimeException("連接失敗 [$errno]: $errstr");
    
    $body = http_build_query($data);
    $contentLength = strlen($body);
    
    $request = "POST $path HTTP/1.1\r\n";
    $request .= "Host: $host\r\n";
    $request .= "User-Agent: PHP-fsockopen/1.0\r\n";
    $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $request .= "Content-Length: $contentLength\r\n";
    $request .= "Connection: Close\r\n";
    $request .= "\r\n";
    $request .= $body;
    
    fwrite($fp, $request);
    
    $response = '';
    while (!feof($fp)) {
        $response .= fgets($fp, 4096);
    }
    fclose($fp);
    
    list($headers, $body) = explode("\r\n\r\n", $response, 2);
    return $body;
}

// 使用
$result = httpPost('api.example.com', '/submit', [
    'username' => 'test',
    'password' => 'secret'
]);
echo $result;
?>

HTTPS 支援 (SSL/TLS)

<?php
function httpRequest(string $url, string $method = 'GET', array $data = []): ?string {
    $parsed = parse_url($url);
    $host = $parsed['host'];
    $path = $parsed['path'] ?? '/';
    if (!empty($parsed['query'])) $path .= '?' . $parsed['query'];
    $port = $parsed['port'] ?? ($parsed['scheme'] === 'https' ? 443 : 80);
    $scheme = $parsed['scheme'] ?? 'http';
    
    // SSL 上下文選項 (生產環境請驗證證書)
    $context = stream_context_create([
        'ssl' => [
            'verify_peer' => false,      // 生產環境設 true
            'verify_peer_name' => false, // 生產環境設 true
            'allow_self_signed' => true
        ]
    ]);
    
    $target = ($scheme === 'https' ? 'ssl://' : '') . $host . ':' . $port;
    $fp = stream_socket_client($target, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
    if (!$fp) throw new RuntimeException("SSL連接失敗 [$errno]: $errstr");
    
    // 構造請求 (同 HTTP,Host 頭需包含端口非標準時)
    $request = "$method $path HTTP/1.1\r\n";
    $request .= "Host: $host\r\n";
    $request .= "User-Agent: PHP-fsockopen/1.0\r\n";
    $request .= "Connection: Close\r\n";
    
    if ($method === 'POST' && $data) {
        $body = http_build_query($data);
        $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $request .= "Content-Length: " . strlen($body) . "\r\n";
        $request .= "\r\n$body";
    } else {
        $request .= "\r\n";
    }
    
    fwrite($fp, $request);
    
    $response = '';
    stream_set_timeout($fp, 30);
    while (!feof($fp)) {
        $response .= fgets($fp, 4096);
    }
    fclose($fp);
    
    // 解析響應
    list($headerStr, $body) = explode("\r\n\r\n", $response, 2);
    return $body;
}
?>

高級特性支援

1. 處理 Chunked Transfer Encoding

<?php
function parseChunkedBody(string $body): string {
    $result = '';
    $pos = 0;
    $len = strlen($body);
    
    while ($pos < $len) {
        // 讀取塊大小行
        $lineEnd = strpos($body, "\r\n", $pos);
        if ($lineEnd === false) break;
        $chunkSizeLine = substr($body, $pos, $lineEnd - $pos);
        $pos = $lineEnd + 2;
        
        $chunkSize = hexdec(trim($chunkSizeLine));
        if ($chunkSize === 0) break; // 最後一塊
        
        // 讀取塊數據
        $result .= substr($body, $pos, $chunkSize);
        $pos += $chunkSize + 2; // 跳過數據後的 \r\n
    }
    return $result;
}
?>

2. 支援 Cookie 會話

<?php
class SimpleHttpClient {
    private $cookieJar = [];
    
    public function request(string $method, string $url, array $data = []): string {
        // ... 建立連接、發送請求 (帶上 $this->cookieJar 對應域名的 Cookie)
        
        // 解析響應頭中的 Set-Cookie
        if (preg_match_all('/Set-Cookie:\s*([^;]+)/i', $headers, $matches)) {
            foreach ($matches[1] as $cookie) {
                [$name, $value] = explode('=', $cookie, 2);
                $this->cookieJar[parse_url($url, PHP_URL_HOST)][$name] = $value;
            }
        }
        return $body;
    }
}
?>

3. 文件上傳

<?php
function httpPostMultipart(string $host, string $path, array $fields, array $files, int $port = 80): ?string {
    $boundary = '----PHPFSOCK' . md5(microtime());
    $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 => $file) {
        $content = file_get_contents($file['tmp_name']);
        $filename = $file['name'];
        $mime = $file['type'] ?? '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";
    
    // 發送請求 (Content-Type: multipart/form-data; boundary=...)
    // ... 類似 httpPost,修改 Content-Type 和 Content-Length
}
?>

現代替代方案對比

方案優點缺點適用場景
fsockopen/stream_socket_client零依賴、完全控制、教學價值高手動處理協議細節、易出錯、無連接池嵌入式、受限環境、協議調試
cURL功能全、性能高、支援並發、成熟穩定需擴展、API 較繁瑣生產環境首選
Guzzle / Symfony HttpClient面向對象、中介軟體、異步、測試友好依賴 Composer、學習曲線現代框架項目
file_get_contents + stream_context簡單 GET/POST、內建功能有限、錯誤處理弱簡單一次性請求

總結

fsockopen 是理解 HTTP 協議、實現輕量客戶端的基石。生產環境強烈建議使用 cURL 或 Guzzle,享受連接復用、自動重試、並發、證書驗證等企業級特性。本文代碼可作為學習參考或極簡環境備選方案。

copyright © 萬盛學電腦網 all rights reserved