早期PHP無cURL擴展時,開發者常用fsockopen手工構造HTTP報文。本文解析一個經典的httpRequest函數實現,指出其局限,並推薦現代替代方案(cURL、Guzzle、Http\Client)。
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;
}
ssl://或tls://協議前綴並驗證證書,極其繁瑣。Location頭並遞歸請求。gzip/deflate。| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| cURL擴展 | 功能全、性能高、原生支持HTTPS/HTTP2/代理/並發 | API較底層、易誤用 | 所有HTTP客戶端需求 |
| Guzzle | PSR-18/17兼容、中間件、異步、重試、測試友好 | 依賴較多、學習曲線 | 現代框架項目、微服務調用 |
| Symfony HttpClient | 零配置、自動解碼、異步、Scoping Client | 需Symfony組件 | Symfony/Laravel項目 |
| ext-http (pecl_http) | C層實現、高性能、完整HTTP/2 | 需編譯擴展、部署複雜 | 極高性能場景 |