php curl模拟 get post请求


if (!function_exists('curl_data')) {
    /**
     * curl 请求
     * Author:刘星麟
     * @param $url
     * @param $data
     * @param string $method 支持 GET  POST  PUT  DELETE
     * @param string $type
     * @return bool|string
     */
    function curl_data($url, $data, $method = 'POST', $type = 'form-data')
    {
        //初始化
        $ch = curl_init();
        header('Content-Type:application/json; charset=utf-8');
        $headers = [
            'form-data' => ['Content-Type: multipart/form-data'], 'json' => ['Content-Type: application/json'],
        ];
        
        //统一转化为大写
        $method = strtoupper($method);
        if ($method == 'GET') {
            if ($data) {
                $querystring = http_build_query($data);
                $url = $url . '?' . $querystring;
            }
        }
        
        // 请求头,可以传数组
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers[$type]);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if ($method == 'PUT') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if ($method == 'DELETE') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);           //最大相应超时时间
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        $output = curl_exec($ch);
        
        curl_close($ch);
        return $output;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值