/**
     * 提交数据---
     * @param  string $url 请求Url
     * @param  array/string $params 请求参数
     * @param  string $method 请求方式
     * @param  array/string $headers Headers信息
     * @return 返回的
     */
    function curl($url = '', $params = '', $method = 'PUT', $sign = '', $headers = '')
    {
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
        );
        $requestString = http_build_query($params);
        if ($method == 'DELETE' && !empty($requestString)) {
            $url = $url . '?' . $requestString;
        }
        $data = json_encode($params);//json格式

        // 启动一个CURL会话
        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($handle, CURLOPT_HEADER, 0); // 是否显示返回的Header区域内容
        curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); //设置请求头
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查

        switch ($method) {
            case 'GET':
                break;
            case 'POST':
                curl_setopt($handle, CURLOPT_POST, true);
                curl_setopt($handle, CURLOPT_POSTFIELDS, $data); //设置请求体,提交数据包
                break;
            case 'PUT':
                curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($handle, CURLOPT_POSTFIELDS, $data); //设置请求体,提交数据包
                break;
            case 'DELETE':
                curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
        }
        $response = curl_exec($handle);
        if (curl_errno($handle)) {
            return array('msg' => curl_error($handle), 'code' => 400, 'data' => '');
        }
        curl_close($handle); // 关闭CURL会话
        if (stristr($response, 'HTTP 404') || $response == '') {
            return array('msg' => '请求错误', 'code' => 0, 'data' => '');
        }
        $response = json_decode($response, true);
        return $response;
    }
Last modification:September 28th, 2019 at 01:10 am
如果觉得我的文章对你有用,请随意赞赏