PHP中使用CURL实现GET、POST、PUT、DELETE请求

/**
 * @param $url
 * @param $data
 * @param string $method
 * @param string $type
 * @param array $headers
 * @return bool|string
 */

function curlpost($url,$data,$method = 'GET',$type='json',$headers=[])
{
    try{
        //初始化
        $ch = curl_init();
        $headers[] =  "cache-control: no-cache";
        $contentType = [
            'form-data' => 'Content-Type: multipart/form-data',
            'json'      => 'Content-Type: application/json',
        ];
        if($method == 'GET'){
            if($data){
                $querystring = http_build_query($data);
                $url = $url.'?'.$querystring;
            }
        }
        $headers[] = $contentType[$type];

        // 请求头,可以传数组
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);         // 执行后不直接打印出来
        if($method == 'POST'){
            if($type=='json'){
                $data = json_encode($data);
            }
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');     // 请求方式
            curl_setopt($ch, CURLOPT_POST, true);               // post提交
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);                 // post的变量
        }
        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_HTTP_VERSION, CURL_HTTP_VERSION_1_1);  // 最大执行时间
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        $output = curl_exec($ch); //执行并获取HTML文档内容
        $err = curl_error($ch);
        if($err){
            //\Illuminate\Support\Facades\Log::info('curl错误');
            //\Illuminate\Support\Facades\Log::error($err);
        }
        curl_close($ch); //释放curl句柄
        return $output;
    }catch (\Exception $e){
        \Illuminate\Support\Facades\Log::info('curl异常');
        \Illuminate\Support\Facades\Log::error($e);
        return false;
    }
}

 

posted @ 2019-07-03 13:49  一天天写BUG  阅读(8817)  评论(0编辑  收藏  举报