PHP Curl 请求封装类实例

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

这是一个简单的 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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。