PHP curl请求
GET请求
function curl_get($url,$res='json',$header = array()){
$oCurl = curl_init();
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
if(stripos($url,"https://")!==FALSE){
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
}
if (!empty($header)) {
curl_setopt($oCurl, CURLOPT_HTTPHEADER, $header);
}
$sContent = curl_exec($oCurl);
// $aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if($res == 'json'){
return json_decode($sContent,true);
}else{
return $sContent;
}
}
POST请求
(提示: x-www-form-urlencoded 方式发送数据,格式为:http_build_query($post_data = array()))
function postCurl($post_data,$url,$res='json',$second=30,$header = ['Content-type:application/x-www-form-urlencoded'])
{
$ch = curl_init(); // 启动一个CURL会话
curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
if (!empty($post_data)) {
if(in_array("content-type: multipart/form-data",$header)){
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);//上传文件或者以上传文件的形式post数据
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
}
// curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($ch, CURLOPT_TIMEOUT, $second); // 设置超时限制防止死循环
$output = curl_exec($ch); // 执行操作
curl_close($ch); // 关闭CURL会话
if ($res == 'json') {
return json_decode($output,true);
}
return $output;
}
webservice请求
function curl_webservice($linId,$orderId)
{
$xmlData = '<xml></xml>';// xml(需求格式数据)
$username = 'username';//如需登录,登录用户名
$password = 'password ';//如需登录,登录密码
$url = 'http://url'; //请求地址,不加?wsdl
$header[] = "Content-type: text/xml";
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $xmlData);
curl_setopt($ch, CURLOPT_USERPWD, "{$username}:{$password}");
$response = curl_exec($ch);
if(curl_errno($ch)){
return curl_error($ch);
}
curl_close($ch);
return $response;
}

浙公网安备 33010602011771号