php 中使用curl的一般步骤
-
curl_init()
初始化curl句柄 -
curl_setopt()
设置请求参数 -
curl_exec()
执行并获取结果 -
curl_close()
关闭crul句柄
CURL GET请求
<?php
/**
*封装cURL的调用接口,get的请求方式。
*/
function GetMetod($url, $data = [], $header = [], $timeout = 5){
if($url == "" || $timeout <= 0){
return false;
}
$url = $url.'?'.http_build_query($data); //http_build_query()传入关联数组,处理请求参数和数据
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); //设置为true将请求结果保存到变量中,否则直接输出
curl_setopt($curl, CURLOPT_TIMEOUT, (int)$timeout);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //添加自定义httpheader
return curl_exec($curl);
}
?>
CURL POST请求
<?php
/**
**封装cURL的调用接口,post的请求方式。
**/
function PostMethod($url, $data = [], $header = [], $timeout = 5){
if($url == '' || $timeout <=0){
return false;
}
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
curl_setopt($curl, CURLOPT_POST,true); //设置POST请求
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_TIMEOUT,(int)$timeout);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //添加自定义httpheader
return curl_exec($curl);
}
?>
CURL POST JSON数据
<?php
$data='{"name":"jmy","msg":"hello"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Content-Length:' . strlen($data)));
curl_setopt($ch, CURLOPT_POSTFIELDS , $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
echo $output;
curl_close($ch);
?>
CURL COOKIE
curl_setopt($curl,CURLOPT_COOKIESESSION,true);
curl_setopt($curl,CURLOPT_COOKIEFILE,'mcookie');
curl_setopt($curl,CURLOPT_COOKIEJAR,'mcookie');
curl_setopt($curl,CURLOPT_COOKIE,session_name().'='.session_id());
在 curl_exec() 执行后还可以使用 curl_getinfo() 函数获取 CURL 请求输出的相关信息。