php 中使用curl的一般步驟
-
curl_init()初始化curl句柄 -
curl_setopt()設置請求參數(shù) -
curl_exec()執(zhí)行并獲取結(jié)果 -
curl_close()關(guān)閉crul句柄
CURL GET請求
<?php
/**
*封裝cURL的調(diào)用接口,get的請求方式。
*/
function GetMetod($url, $data = [], $header = [], $timeout = 5){
if($url == "" || $timeout <= 0){
return false;
}
$url = $url.'?'.http_build_query($data); //http_build_query()傳入關(guān)聯(lián)數(shù)組,處理請求參數(shù)和數(shù)據(jù)
$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將請求結(jié)果保存到變量中,否則直接輸出
curl_setopt($curl, CURLOPT_TIMEOUT, (int)$timeout);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //添加自定義httpheader
return curl_exec($curl);
}
?>
CURL POST請求
<?php
/**
**封裝cURL的調(diào)用接口,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數(shù)據(jù)
<?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() 執(zhí)行后還可以使用 curl_getinfo() 函數(shù)獲取 CURL 請求輸出的相關(guān)信息。