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

原创
2016/01/28 10:55
阅读数 1.7K
if(!function_exists('CurlHttp'))
{

    function CurlHttp($url,$method='GET',$data='',$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_TIMEOUT, $timeout);//超时设置
            $headers = array();
            foreach($header as $key=>$value){
                $headers[] = $key.' : '. $value;
            }
            if(is_array($data)){
                $temp = array();
                foreach($data as $key=>$value)
                {
                    $temp[] = $key.'='.$value;
                }
                $params = implode('&',$temp);
                unset($temp);
            }else{
                $params = $data;
            }
            curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);//设置HTTP头信息
            switch ($method){
                //case "GET" :
                    //curl_setopt($ch, CURLOPT_HTTPGET, true);break;
                case "POST":
                    curl_setopt($ch, CURLOPT_POST,true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
                case "PUT" :
                    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
                case "DELETE":
                    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
                default :
                    curl_setopt($ch, CURLOPT_HTTPGET, true);break;
            }

            $response = curl_exec($ch);//执行预定义的CURL
            $info = curl_getinfo($ch);
            $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;
    }
}


展开阅读全文
打赏
1
6 收藏
分享
加载中
更多评论
打赏
0 评论
6 收藏
1
分享
返回顶部
顶部