简单封装CURL请求,以及php获取url重定向后的链接
mini胖发表于:2022-04-07 14:50:25浏览:1469次
简单封装CURL请求,支持post与get
常用于请求微信API
//使用 curl 方法
function http_curl($url,$type='get',$res='json',$arr=''){
//初始化 curl
$ch = curl_init();
//设置curl的参数
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//处理证书问题
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//处理结束
if($type == 'post'){
//type 为post
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
}
//采集
$output = curl_exec($ch);
//关闭
//curl_close($ch);
if(curl_errno($ch)){
return curl_errno($ch); //报错
}else{
return json_decode($output,true); //ok
}
}
php获取url重定向后的链接
通过当前方法可以获取真实访问链接
get_to_url($url);
function get_to_url($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64; rv:21.0) Gecko/20100101 Firefox/21.0"); // Necessary. The server checks for a valid User-Agent.
curl_exec($ch);
$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
curl_close($ch);
return !empty($matches[1]) ? trim($matches[1][0]) : '';
}
function http_post($sUrl, $aHeader, $aData){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $sUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($aData));
$sResult = curl_exec($ch);
if($sError=curl_error($ch)){
die($sError);
}
curl_close($ch);
return $sResult;
}
$url = 'https://www.example.com;
$header = array('User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36');
$data = array();
$data = http_post($url,$header,$data);