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_exec):功能更全、性能更好、支援 HTTPS/HTTP2/多路復用。