基於 HTTP 1.1 協議實作的遠程檔案下載類,支援斷點續傳、錯誤處理、多種使用模式。核心利用 fsockopen() 建立 Socket 連線,手動構造 HTTP 請求與解析回應。
<?php
class HttpDownload {
private $m_url, $m_host, $m_port = 80, $m_path = '/', $m_query = '';
private $m_fp, $m_error, $m_httphead = [], $m_html = '';
// 解析 URL 初始化屬性
private function PrivateInit($url) { /* parse_url 解析 host, path, query, port... */ }
// 建立 Socket 連線並發送 HTTP GET 請求
private function PrivateStartSession() {
$this->m_fp = @fsockopen($this->m_host, $this->m_port, $errno, $errstr, 10);
if (!$this->m_fp) { $this->m_error = $errstr; return false; }
$httpv = $this->GetHead('http-edition') ?: 'HTTP/1.0';
fputs($this->m_fp, "GET {$this->m_urlpath} $httpv\r\n");
fputs($this->m_fp, "Host: {$this->m_host}\r\n");
fputs($this->m_fp, "Accept: */*\r\n");
fputs($this->m_fp, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2)\r\n");
// HTTP/1.1 必須指定 Connection: Close,否則 feof 無法判斷結束
fputs($this->m_fp, $httpv == 'HTTP/1.1' ? "Connection: Close\r\n\r\n" : "\r\n");
// 解析回應標頭
$status = fgets($this->m_fp, 256);
// ... 解析狀態碼、標頭至空行 ...
}
// 公開方法
public function OpenUrl($url) { /* 重設屬性 -> PrivateInit -> PrivateStartSession */ }
public function IsGetOK() { return preg_match('/^2/', $this->GetHead('http-state')); }
public function IsText() { return $this->IsGetOK() && stripos($this->GetHead('content-type'), 'text') === 0; }
public function GetHead($name) { return $this->m_httphead[strtolower($name)] ?? ''; }
public function GetHtml() { /* 讀取 body 至 feof */ }
public function SaveToBin($savefilename) { /* 二進位儲存,支援斷點續傳邏輯 */ }
public function SaveToText($savefilename) { /* 文字儲存 */ }
public function printError() { /* 輸出錯誤與標頭 */ }
public function Close() { @fclose($this->m_fp); }
}
?>
$http = new HttpDownload();
$http->OpenUrl('https://www.google.com.hk');
echo $http->GetHtml();
$http->Close();
$dl = new HttpDownload();
$dl->OpenUrl('https://example.com/largefile.zip');
$dl->SaveToBin('largefile.zip'); // 內部處理 Range 請求與續傳
$dl->Close();
feof() 才能正常判斷結束。Range: bytes=已下載位置-,伺服器回傳 206 Partial Content 並附 Content-Range。printError() 輸出狀態碼、描述、完整回應標頭,利於除錯。fsockopen() 第 5 參數設定連線逾時(秒)。curl_setopt($ch, CURLOPT_RANGE, "$start-") 原生支援斷點續傳,更穩健、效能更好。