萬盛學電腦網

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

PHP 封装 HttpClient 类:支持 GET/POST/Cookie/Session 的轻量级 HTTP 客户端

设计特点

  • 面向对象封装请求/响应/上下文
  • 自动管理 Cookie 会话(模拟浏览器行为)
  • 支持自定义 Header、User-Agent、Referer
  • 基于原生 fsockopen/stream_socket_client,无需 cURL 扩展

核心类结构

<?php
// Cookie 对象
class SinCookie {
    public $name, $value, $expires, $path, $domain;
    public function __construct($s = false) {
        if ($s) {
            $i1 = strpos($s, '=');
            $i2 = strpos($s, ';');
            $this->name  = trim(substr($s, 0, $i1));
            $this->value = trim(substr($s, $i1 + 1, $i2 - $i1 - 1));
        }
    }
    public function getKeyValue() { return "$this->name=$this->value"; }
}

// 会话上下文:保持 Cookie、Referer
class SinHttpContext {
    public $cookies = array();
    public $referer = '';
    public function cookie($key, $val) {
        $ck = new SinCookie();
        $ck->name = $key; $ck->value = $val;
        $this->cookies[$key] = $ck;
    }
    public function cookiesString() {
        $res = '';
        foreach ($this->cookies as $ck) $res .= $ck->getKeyValue() . '; ';
        return $res;
    }
}

// 请求对象
class SinHttpRequest {
    public $url, $method = 'GET', $header = array(), $body = '';
    public function setHeader($k, $v) { $this->header[$k] = $v; }
    public function reqString() {
        $m = parse_url($this->url);
        $host = $m['host']; $path = $m['path'] . ($m['query'] ? '?' . $m['query'] : '');
        $port = isset($m['port']) ? $m['port'] : 80;
        $req = "{$this->method} $path HTTP/1.1\r\nHost: $host\r\n";
        foreach ($this->header as $k => $v) $req .= "$k: $v\r\n";
        $req .= "Connection: Close\r\n\r\n" . $this->body;
        return $req;
    }
}

// 响应对象
class SinHttpResponse {
    public $header = array(), $body = '', $code = 0;
    public function __construct($raw) {
        list($head, $this->body) = explode("\r\n\r\n", $raw, 2);
        $lines = explode("\r\n", $head);
        $this->code = (int)substr($lines[0], 9, 3);
        foreach (array_slice($lines, 1) as $l) {
            if (($p = strpos($l, ':')) !== false) {
                $this->header[trim(substr($l, 0, $p))] = trim(substr($l, $p + 1));
            }
        }
        // 自动处理 Set-Cookie
        if (isset($this->header['Set-Cookie'])) {
            foreach (explode("\n", $this->header['Set-Cookie']) as $c) {
                $ctx->cookie(...); // 交给上下文处理
            }
        }
    }
}

// 客户端入口
class SinHttpClient {
    private $ctx;
    public function __construct() { $this->ctx = new SinHttpContext(); }
    public function get($url) {
        $req = new SinHttpRequest(); $req->url = $url; $req->method = 'GET';
        return $this->execute($req);
    }
    public function post($url, $data) {
        $req = new SinHttpRequest(); $req->url = $url; $req->method = 'POST';
        $req->body = is_array($data) ? http_build_query($data) : $data;
        $req->setHeader('Content-Type', 'application/x-www-form-urlencoded');
        $req->setHeader('Content-Length', strlen($req->body));
        return $this->execute($req);
    }
    private function execute($req) {
        $req->setHeader('User-Agent', 'Mozilla/5.0 (compatible; SinHttpClient)');
        $req->setHeader('Cookie', $this->ctx->cookiesString());
        $req->setHeader('Referer', $this->ctx->referer);
        $fp = fsockopen($req->host, $req->port, $errno, $errstr, 30);
        if (!$fp) throw new Exception("Connect failed: $errstr");
        fwrite($fp, $req->reqString());
        $resp = '';
        while (!feof($fp)) $resp .= fread($fp, 8192);
        fclose($fp);
        $resObj = new SinHttpResponse($resp);
        $this->ctx->referer = $req->url;
        return $resObj;
    }
}

使用示例

$client = new SinHttpClient();
// 登录获取 Cookie
$res = $client->post('https://example.com/login', array('user'=>'admin','pass'=>'123456'));
// 后续请求自动携带 Cookie
$res = $client->get('https://example.com/user/profile');
echo $res->body;

现代替代建议

新项目强烈推荐 Guzzle 或 Symfony HttpClient,支持 PSR-18、异步、中间件、重试、测试双工等企业级特性。

copyright © 萬盛學電腦網 all rights reserved