今天分享几个用php编程封装好的post,get封装请求;直接拿来可以使用的curl请求封装。
post_curl提交数据请求
function post_curl($url, $params=[], $headers=[],$cookie){
$httpInfo = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
curl_setopt( $ch , CURLOPT_POST , true );
curl_setopt( $ch , CURLOPT_POSTFIELDS , http_build_query($params));
curl_setopt( $ch , CURLOPT_URL , $url );
$response = curl_exec( $ch );
if ($response === FALSE) {
return false;
}
curl_close( $ch );
return $response;
}
代码中的$url
是需要请求的网址,$params
是post提交的数据实例:
$params=[
'appid'=>'1232132132',
'key'=>'ffghfg4h545dfh12fgdh',//前面是提交的参数,后面是需要提交的数据
];
$headers=[]
的用法跟$params
一致 ,post、get请求一样。
$cookie
的实例:
function getCookie(){
$url = get_curl('需要获取cookies的网站域名', [] , 1);
list($header, $body) = explode("\r\n\r\n", $url);
$matches = explode("\r\n",$header);
preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
$matches = explode(" ",$matches[1]);
return $matches[1];
}
用法实例:
$cookie = getCookie();//取cookie
get_curl请求
用法跟post一致
function get_curl($url, $params=[], $headers=[],$cookie = ''){
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HEADER, 1);
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true);
curl_setopt( $ch, CURLOPT_NOBODY , true);
curl_setopt( $ch, CURLOPT_POST , false );
curl_setopt( $ch, CURLOPT_POSTFIELDS , http_build_query($params));
curl_setopt( $ch, CURLOPT_URL , $url );
$response = curl_exec( $ch );
curl_close( $ch );
return $response;
}