curl 请求,兼容get ,post ,put patch,delete

function CurlHttp($url,$method='get',$data=array(),$header=array(),$timeout=5)
    {
        $response = '';
        try{
            $ch = curl_init(); //初始化CURL句柄
            curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
            if($method == 'post'){
                $header['Content-Type']='application/x-www-form-urlencoded';
            }
            $header['X-HTTP-Method-Override'] = $method;
            foreach($header as $key=>$value){
                $header[$key] = $key.':'. $method;
            }
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);//设置HTTP头信息
            if($method == 'post'){
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
            }
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            $response = curl_exec($ch);//执行预定义的CURL
            $errno = curl_errno($ch);
            if($errno){
                throw new Exception(curl_getinfo($ch),$errno);
            }
            curl_close($ch);
        }catch(Exception $e){
            $errArr = array(
                'curlerrno'=>$e->getCode(),
                'curlinfo' =>$e->getMessage()
            );
            Log::errro('curlerror',$errArr);
        }
        return $response;
    }


你可能感兴趣的:(curl 请求,兼容get ,post ,put patch,delete)