PHP支持的由Daniel Stenberg創(chuàng)建的libcurl庫(kù)允許你與各種的服務(wù)器使用各種類(lèi)型的協(xié)議進(jìn)行連接和通訊。
libcurl目前支持http、https、ftp、gopher、telnet、dict、file和ldap協(xié)議。libcurl同時(shí)也支持HTTPS認(rèn)證、HTTP POST、HTTP PUT、 FTP 上傳(這個(gè)也能通過(guò)PHP的FTP擴(kuò)展完成)、HTTP 基于表單的上傳、代理、cookies和用戶(hù)名+密碼的認(rèn)證。
因?yàn)樾枰?php 開(kāi)發(fā)中對(duì)接其它接口需要用 php curl 去對(duì)接其它接口 我把他們封裝成函數(shù) 希望能對(duì)大家有所幫助。
?php
function geturl($url){
$headerArray =array("Content-type:application/json;","Accept:application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output,true);
return $output;
}
function posturl($url,$data){
$data = json_encode($data);
$headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return json_decode($output,true);
}
function puturl($url,$data){
$data = json_encode($data);
$ch = curl_init(); //初始化CURL句柄
curl_setopt($ch, CURLOPT_URL, $url); //設(shè)置請(qǐng)求的URL
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //設(shè)為T(mén)RUE把curl_exec()結(jié)果轉(zhuǎn)化為字串,而不是直接輸出
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //設(shè)置請(qǐng)求方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//設(shè)置提交的字符串
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output,true);
}
function delurl($url,$data){
$data = json_encode($data);
$ch = curl_init();
curl_setopt ($ch,CURLOPT_URL,$put_url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output,true);
}
function patchurl($url,$data){
$data = json_encode($data);
$ch = curl_init();
curl_setopt ($ch,CURLOPT_URL,$url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data); //20170611修改接口,用/id的方式傳遞,直接寫(xiě)在url中了
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output);
return $output;
}
?>
以上就是PHP利用curl發(fā)送HTTP請(qǐng)求的實(shí)例代碼的詳細(xì)內(nèi)容,更多關(guān)于PHP 發(fā)送HTTP請(qǐng)求的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!