PHP的curl功能提供了不少函數,須要將這些函數按特定的步驟組合到一塊兒,咱們先來了解下PHP創建curl請求的基本步驟。json
$ch = curl_init(); // 建立一個新的CURL資源賦給變量$ch
curl_setopt($ch, CURLOPT_URL, $url); // 設置URL
$response = curl_exec($ch); // 執行,獲取URL並輸出到瀏覽器
curl_close($ch); // 釋放資源
若是咱們但願獲取內容但不輸出,能夠使用 CURLOPT_RETURNTRANSFER 參數,並設置其值爲非0或者true值。代碼以下:curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
瀏覽器
咱們能夠通設置函數curl_setopt()的不一樣參數,能夠得到不一樣的結果,這也是CURL擴展的強大之處。curl_setopt()函數的經常使用參數選項具體可查閱官方文檔,此處就不列舉。app
下面是我經常使用的curl get和post請求的方法:curl
get請求:函數
public function httpGet(string $url = '') { // 記錄請求信息的日誌 // todo try { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 60); //https 請求 if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } $response = curl_exec($ch); $errorCode = curl_errno($ch); curl_close($ch); if (!empty($errorCode)) { // 可記錄錯誤碼日誌 return null; } // 記錄返回結果日誌 return $response; } catch (\Exception $e) { $errorLog = [ 'msg' => $e->getMessage(), 'trace' => $e->getTraceAsString(), 'data' => [ 'url' => $url, ] ]; // 記錄錯誤日誌 return null; } }
POST請求:post
public function httpPost(string $url = '', array $data = []) { // 記錄請求信息的日誌 // todo try { $jsonData = json_encode($data); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_TIMEOUT, 60); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json; charset=utf-8', 'Content-Length:' . strlen($jsonData) ]); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //https 請求 if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); } $result = curl_exec($curl); $errorCode = curl_errno($curl); curl_close($curl); if (!empty($errorCode)) { // 可記錄錯誤碼日誌 return null; } // 記錄返回結果日誌 return json_decode($result, true); } catch (\Exception $e) { $errorData = [ 'msg' => $e->getMessage(), 'trace' => $e->getTraceAsString(), 'data' => [ 'url' => $url, 'postData' => $data ] ]; // 記錄錯誤日誌 return null; } }
歡迎各位朋友進行交流。url