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;
}
}
转载于:https://my.oschina.net/u/998304/blog/610743