PHP curl请求post get 文件上传统一封装

5 篇文章 0 订阅

    /**
     * 模拟POST与GET请求
     * @param string $url [请求地址]
     * @param string $type [请求方式 post or get]
     * @param bool|string|array $data [传递的参数]
     * @param array $header [可选:请求头] eg: ['Content-Type:application/json']
     * @param int $timeout [可选:超时时间]
     */
    public function request($url, $type, $data = false, $header = [], $timeout = 0)
    {
        $cl = curl_init();
        // 兼容HTTPS
        if (stripos($url, 'https://') !== FALSE) {
            curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($cl, CURLOPT_SSLVERSION, 1);

        }
        // 设置返回内容做变量存储
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
        // 设置需要返回Header
        curl_setopt($cl, CURLOPT_HEADER, true);
        // 设置请求头
        // 设置请求头
        if (count($header) > 0) {
            curl_setopt($cl, CURLOPT_HTTPHEADER, $header);
        }
        // 设置需要返回Body
        curl_setopt($cl, CURLOPT_NOBODY, 0);
        // 设置超时时间
        if ($timeout > 0) {
            curl_setopt($cl, CURLOPT_TIMEOUT, $timeout);
        }
        // POST/GET参数处理
        $type = strtoupper($type);
        if ($type == 'POST') {
            if (is_array($data))
            {
                $data = http_build_query($data, null, '&');
            }
            curl_setopt($cl, CURLOPT_POSTFIELDS, $data);
        }
        if ($type == 'GET' && is_array($data)) {
            if (stripos($url, "?") === FALSE) {
                $url .= '?';
            }
            $url .= http_build_query($data);
        }
        curl_setopt($cl, CURLOPT_URL, $url);
        //在http 请求头加入 gzip压缩
        //curl_setopt($cl, CURLOPT_HTTPHEADER, array('Accept-Encoding:gzip'));
        //curl返回的结果,采用gzip解压
        //curl_setopt($cl, CURLOPT_ENCODING, "gzip");
        // 读取获取内容
        $response = curl_exec($cl);
        // 读取状态
        $status = curl_getinfo($cl);
        // 读取错误号
        $errno = curl_errno($cl);
        // 读取错误详情
        $error = curl_error($cl);
        // 关闭Curl
        curl_close($cl);
        if ($errno == 0 && isset($status['http_code'])) {
            $header = substr($response, 0, $status['header_size']);
            $body = substr($response, $status['header_size']);
         	$array_data = json_decode(json_encode(simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            return $array_data;
        } else {
            return array('', '', $status, $errno, $error);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值