首页 » 收集 » 正文内容
PHP封装一个POST,GET,PUT,DELETE的CURL函数
寻梦xunm| 672| 收集
3年前
超过1105天 温馨提示
本文最后更新于2021年09月11日,已超过1105天没有更新,若内容或图片失效,请留言反馈。

由于工作原因,做得比较多的都是接口和接口之前的数据交互,所以要经常用到curl,所以把curl封装了一下以便使用。一下返回可以设置返回数组或者json格式。

<?php
/**
     * Notes: 封装PHPCurl请求
     * Author: nobita
     * Date: 2019/7/23 10:58
     * @param $url
     * @param null $data
     * @param string $method
     * @param bool $jsonFormat
     * @param string $header
     * @param bool $https
     * @param int $timeout
     * @return bool|mixed|string
     */
    function network_request($url, $data = null, $method = 'get', $jsonFormat = true, $header = '', $https = false, $timeout = 15)
    {
        $method = strtoupper($method);
        $ch = curl_init();//初始化
        curl_setopt($ch, CURLOPT_URL, $url);//访问的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容,但不输出
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https请求 不验证HOST
        }
        if ($method != "GET") {
            if ($method == 'POST') {
                curl_setopt($ch, CURLOPT_POST, true);//请求方式为post请求
            }
            if ($method == 'PUT' || strtoupper($method) == 'DELETE') {
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
            }
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//请求数据
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        } else {
            curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
        }
        $result = curl_exec($ch);//执行请求
        curl_close($ch);//关闭curl,释放资源
        if (!$jsonFormat) {
            return $result;
        }
        return json_decode($result, true);
}

用法

<?php
network_request($api,$queryParams,'post')

文章来源于:https://199508.com/post/2063

0 赞 or 打赏
喜欢就打赏一点
微信 支付宝
隐私
Q Q:1340326824
邮箱:vipshiyi@qq.com
QQ群:422720328

我的音乐

微博客-专为自己编写开发的源码