stream_context + file_get_contents,無需 cURL 擴展、無需 Guzzle<?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;
}
}
$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";
$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);
// 擴展:支援文件上傳
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() 邏輯
}
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 本類 (Stream) | 零依賴、標準庫、部署極簡、PHAR 打包友好 | 無連接池、無異步、無自動重試、HTTP/2 不支援 | CLI 腳本、Serverless、輕量容器、遷移舊項目 |
| cURL 擴展 | 功能全、性能高、支援 HTTP/2、連接復用、證書管理 | 需安裝擴展、API 較繁瑣 | 高併發、長連接、複雜 TLS 需求 |
| Guzzle / Symfony HttpClient | PSR-18 標準、中間件、異步、重試、測試雙工 | Composer 依賴、體積大、學習曲線 | 現代框架專案 (Laravel/Symfony/API Platform) |
stream_context_set_option)HttpClient 類演示了 PHP **Stream Context** 的強大能力:無需任何擴展即可實現完整 HTTP 客戶端功能。對於 CLI 工具、Serverless 函數、極簡部署環境,它是 **Guzzle 的零依賴替代品**。生產級高併發服務建議遷移至 Guzzle/Symfony HttpClient 或 Swoole 協程客戶端,獲得連接池、異步、HTTP/2 等高級特性。