引言

自己写了个模拟请求的php工具类,可用于模拟浏览器的GETPOST等请求

用于在服务端请求别的接口。

优点

  1. 静态调用即可
  2. 支持curl扩展检测,不存在扩展时抛出异常(GET请求会兼容使用别的函数)
  3. POST请求数据支持传入关联数组,自动json
  4. 不需要参数的POST请求,支持body自动生成{}

用法

// 模拟POST请求
$result =\app\util\Req::curl([
    'url' => 'test.com/a.php',
    'data' => [
        'a' => 1, 
        'b' => 2
    ],
    'method' => 'post',
]);

// 模拟GET请求
$result = \app\util\Req::fgc('test.com/a.php', [
    'name' => '张三'
]);
<?php

namespace app\util;

/**
 * 模拟请求的类库(curl)
 */
class Req
{

    // 直接使用 file_get_content 函数
    public static function fgc($url = '', $params = [])
    {
        if (empty($url)) return false;
        if (!function_exists('file_get_contents')) throw new \Exception('file_get_contents函数错误');

        // 构造查询字符串
        if ($params) $url .= '?' . http_build_query($params);

        return file_get_contents($url);
    }

    /**
     * 实际发起请求方法
     *
     * 传入:
     * options: 请求参数
     *  url: 请求链接
     *  data: 请求体数据
     *  method: 请求方法
     *  header: 请求头
     *  need_param: 如果没有传递数据,在body里写入 '{}'
     */
    public static function curl($options = [])
    {
        // 检测 curl 扩展
        self::checkCurlExtension();

        // 获取参数
        $url = $options['url'] ?? [];
        $parm = $options['data'] ?? [];
        $method = $options['method'] ?? 'get';
        $headerOptions = $options['header'] ?? [];
        $needParam = $options['need_param'] ?? false;

        $method = self::dealMethodStr($method);
        if (empty($method) || empty($url)) return false;

        // 初始化 curl
        $ch = curl_init();
        // 设置将结果返回,不显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 如果是 https 协议,则设置跳过 https 证书的验证
        if (substr($url, 0, 5) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }

        //设置请求方式
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        // 自动设置Referer
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);

        if ($method == "GET") {
            $url = dealStr($url, '/');
            $url = dealStr($url, '?');
            $url = dealStr($url, '#');
            if ($parm) $url .= '?' . http_build_query($parm);
            elseif ($needParam) curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");
        } elseif ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1);
            if ($parm) $parm = json_encode($parm, JSON_UNESCAPED_UNICODE);

            if ($parm) curl_setopt($ch, CURLOPT_POSTFIELDS, $parm);
            elseif ($needParam) curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");

        } elseif ($method == "PUT") {
            curl_setopt($ch, CURLOPT_HEADER, false);
            if ($parm) $parm = json_encode($parm, JSON_UNESCAPED_UNICODE);
            $headerOptions[] = 'Content-Length: ' . strlen($parm);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $parm);
        } elseif ($method == "DELETE") {
            if ($parm) $parm = json_encode($parm, JSON_UNESCAPED_UNICODE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $parm);
        }

        // 设置请求头
        self::setHeaderOptions($ch, $headerOptions);

        //设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        // 设置访问的 URL
        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行采集
        $res = curl_exec($ch);
        // 关闭资源
        curl_close($ch);

        return $res;
    }

    // 处理方法
    private static function dealMethodStr($method='')
    {
        if (empty($method)) return false;

        $method = strtoupper($method);

        if (!in_array($method, ['GET', 'POST', 'PUT','DELETE'])) return false;

        return $method;
    }

    // 检测 curl 扩展是否打开
    private static function checkCurlExtension()
    {
        // curl扩展未打开
        if (!extension_loaded('curl')) throw new \Exception('未开启curl扩展', 500);

        return true;
    }

    private static function setHeaderOptions($ch = null, $options = [])
    {
        $header = [
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8'
        ];

        $header = array_merge($header, $options);

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLINFO_HEADER_OUT, false);
    }
}

欢迎关注拓行公众号,分享各种技术博客文章

拓行——奋勇进取,开拓未来,砥砺前行

最后修改:2024 年 03 月 20 日
如果您对各种技术博客文章感兴趣,欢迎关注拓行公众号,分享各种专业技术知识~