PHP Curl 请求封装类实例

远山来客
远山来客
发布时间:2026-10-13 | 2人浏览过
原创

这是一个简单的 PHP 类,用于封装 CURL 扩展,简化发起 HTTP 请求的流程,支持 GET、POST、HEAD 方法及响应头解析。

功能目标

该类的主要目标是降低使用原生 CURL 函数的重复代码,提供统一的接口处理常见的网络请求场景。其核心能力包括:

  • 自动初始化与关闭 CURL 句柄。
  • 支持 GET/POST/HEAD 标准请求方法。
  • 内置简单的响应头解析函数。
  • 支持基础 Cookie 读取与写入。

核心实现代码

<?php
/**
* @description: 封装CURL扩展
*/
class Curl {
    /**
    * @请求的host
    */
    private $host_;
    /**
    * @curl 句柄
    */
    private $ch_;
    /**
    * @超时限制时间
    */
    const time_ = 5;
    /**
    * @请求的设置
    */
    private $options_;
    /**
    * @保存请求头信息
    */
    private $request_header_;
    /**
    * @保存响应头信息
    */
    private $response_header_;
    /**
    * @body_ 用于保存curl请求返回的结果
    */
    private $body_;
    /**
    * @读取cookie
    */
    private $cookie_file_;
    /**
    * @写入cookie
    */
    private $cookie_jar_;

    public function Start($url) {
        $this->ch_ = curl_init($url);
        curl_setopt($this->ch_, CURLOPT_HEADER, 1);
        curl_setopt($this->ch_, CURLOPT_RETURNTRANSFER , 1 );
    }

    public function ResponseHeader($url) {
        if (!function_exists('http_parse_headers')) {
            function http_parse_headers ($raw_headers) {
                $headers = array();
                foreach (explode("\n", $raw_headers) as $i => $h) {
                    $h = explode(':', $h, 2);
                    if (isset($h[1])) {
                        if(!isset($headers[$h[0]])) {
                            $headers[$h[0]] = trim($h[1]);
                        } else if(is_array($headers[$h[0]])) {
                            $tmp = array_merge($headers[$h[0]],array(trim($h[1])));
                            $headers[$h[0]] = $tmp;
                        } else {
                            $tmp = array_merge(array($headers[$h[0]]),array(trim($h[1])));
                            $headers[$h[0]] = $tmp;
                        }
                    }
                }
                return $headers;
            }
        }
        $this->Start($url);
        curl_setopt($this->ch_, CURLOPT_TIMEOUT, Curl::time_);
        $this->body_=$this->Execx();
        $header_size = curl_getinfo($this->ch_, CURLINFO_HEADER_SIZE);
        $this->response_header_ = substr($this->body_, $start = 0, $offset = $header_size);
        $this->response_header_ = http_parse_headers($this->response_header_);
        print_r($this->response_header_);
        return $this->Close($this->body_);
    }

    public function LoadCookie($url,$cookie_file) {
        $this->Start($url);
        curl_setopt($this->ch_, CURLOPT_COOKIE, 1);
        curl_setopt($this->ch_, CURLOPT_COOKIEFILE , $cookie_file);
        $this->body_=$this->Execx();
        return $this->Close($this->body_);
    }

    public function SaveCookie($url) {
        $this->Start($url);
        curl_setopt($this->ch_, CURLOPT_COOKIE, 1);
        curl_setopt($this->ch_, CURLOPT_COOKIEFILE ,'cookie.txt');
        curl_setopt($this->ch_, CURLOPT_COOKIEJAR , 'cookie.txt');
        $this->body_=$this->Execx();
        return $this->Close($this->body_);
    }

    public function SetHeader($headers = null) {
        if (is_array($headers) && count($headers) > 0) {
            curl_setopt($this->ch_, CURLOPT_HTTPHEADER, $headers);
        }
    }

    public function Get($url, array $params = array()) {
        if ($params) {
            if (strpos($url, '?')) {
                $url .= "&".http_build_query($params);
            }
            else {
                $url .= "?".http_build_query($params);
            }
        }
        $this->Start($url);
        curl_setopt($this->ch_, CURLOPT_TIMEOUT, Curl::time_);
        if (strpos($url, 'https') === 0) {
            curl_setopt($this->ch_, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($this->ch_, CURLOPT_SSL_VERIFYPEER, 0);
        }
        $this->body_=$this->Execx();
        return $this->Close($this->body_);
    }

    public function Post($url, array $params = array()) {
        $this->Start($url);
        curl_setopt($this->ch_, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($this->ch_, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
        curl_setopt($this->ch_, CURLOPT_POST, true);
        curl_setopt($this->ch_, CURLOPT_TIMEOUT, Curl::time_);
        if ($params) {
            curl_setopt($this->ch_, CURLOPT_POSTFIELDS, http_build_query($params));
        }
        $this->body_=$this->Execx();
        return $this->Close($this->body_);
    }

    public function Head($url, array $params = array()) {
        $this->Start($url);
        curl_setopt($this->ch_, CURLOPT_TIMEOUT, Curl::time_);
        curl_setopt($this->ch_, CURLOPT_RETURNTRANSFER , 0);
        curl_setOpt($this->ch_,CURLOPT_NOBODY, true);
        $this->body_=$this->Execx();
        return $this->Close($this->body_);
    }

    public function Execx(){
        return curl_exec($this->ch_);
    }

    public function Close($body_){
        if ($body_ === false) {
            echo "CURL Error: " . curl_error($body_);
            return false;
        }
        curl_close($this->ch_);
        return $body_;
    }
}
?>

使用说明

此类的使用较为直接,主要在于配置选项和获取结果:

  1. 创建对象:直接实例化 Curl 类。
  2. 执行请求:调用 Get()、Post() 等方法传入 URL 参数。
  3. 处理 Cookie:若需保持会话,可先调用 LoadCookie(),后续调用 SaveCookie()。
  4. 自定义头部:通过 SetHeader() 设置所需的 HTTP Header。

注意事项

在使用时请注意以下几点以确保稳定性: 1. SSL 验证在该代码中默认关闭(CURLOPT_SSL_VERIFYHOST 和 CURLOPT_SSL_VERIFYPEER 设为 0),这在生产环境中可能带来安全风险,建议根据实际需求调整。 2. 类内定义的辅助函数 http_parse_headers 使用了条件判断防止重定义,但在全局环境下直接定义函数并非最佳实践。

以上就是 PHP Curl 扩展类封装的详细应用介绍,更多关于 PHP 开发技术的资料请关注本站其它相关文章!
相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表