本文實例講述了PHP封裝cURL工具類。分享給大家供大家參考,具體如下:
CurlUtils工具類:
<?php/** * cURL請求工具類 */class CurlUtils { private $ch;//curl資源對象 /** * 構造方法 * @param string $url 請求的地址 * @param int $responseHeader 是否需要響應頭信息 */ public function __construct($url,$responseHeader = 0){ $this->ch = curl_init($url); curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,1);//設置以文件流的形式返回 curl_setopt($this->ch,CURLOPT_HEADER,$responseHeader);//設置響應頭信息是否返回 } /** * 析構方法 */ public function __destruct(){ $this->close(); } /** * 添加請求頭 * @param array $value 請求頭 */ public function addHeader($value){ curl_setopt($this->ch, CURLOPT_HTTPHEADER, $value); } /** * 發送請求 * @return string 返回的數據 */ private function exec(){ return curl_exec($this->ch); } /** * 發送get請求 * @return string 請求返回的數據 */ public function get(){ return $this->exec(); } /** * 發送post請求 * @param arr/string $value 準備發送post的數據 * @param boolean $https 是否為https請求 * @return string 請求返回的數據 */ public function post($value,$https=true){ if($https){ curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE); } curl_setopt($this->ch,CURLOPT_POST,1);//設置post請求 curl_setopt($this->ch,CURLOPT_POSTFIELDS,$value); return $this->exec(); } /** * 關閉curl句柄 */ private function close(){ curl_close($this->ch); }}調用實例:
face++的人臉識別接口
$curl = new CurlUtils("https://api-cn.faceplusplus.com/facepp/v3/detect");//創建curl對象$value = ['api_key'=>'4Y7GS2sAPGEl-BtQlNw5Iqtq5jGOn87z','api_secret'=>'oQnwwJhS2mcm4vflKvgm972up9sLN8zj','image_url'=>'http://avatar.csdn.net/9/7/5/1_baochao95.jpg','return_attributes'=>'gender,age,glass'];//準備post的值echo $curl->post($value);//發送請求
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選