curl 獲取 https 請求方法

curl 獲取 https 請求方法php


今日在作一個項目,須要curl獲取第三方的API,對方的API是https方式的。
算法

以前使用curl能獲取http請求,但今天獲取https請求時,出現瞭如下的錯誤提示:證書驗證失敗。
api

[plain] view plain copy 在CODE上查看代碼片派生到個人代碼片curl

  1. SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed  ui


解決方法,在curl請求時,加入
加密

[php] view plain copy 在CODE上查看代碼片派生到個人代碼片url

  1. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳過證書檢查  spa

  2. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 從證書中檢查SSL加密算法是否存在  .net


curl https請求代碼
code

[php] view plain copy 在CODE上查看代碼片派生到個人代碼片

  1. <?php  

  2. /** curl 獲取 https 請求 

  3. * @param String $url        請求的url 

  4. * @param Array  $data       要發送的數據 

  5. * @param Array  $header     請求時發送的header 

  6. * @param int    $timeout    超時時間,默認30s 

  7. */  

  8. function curl_https($url$data=array(), $header=array(), $timeout=30){  

  9.   

  10.     $ch = curl_init();  

  11.     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳過證書檢查  

  12.     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 從證書中檢查SSL加密算法是否存在  

  13.     curl_setopt($ch, CURLOPT_URL, $url);  

  14.     curl_setopt($ch, CURLOPT_HTTPHEADER, $header);  

  15.     curl_setopt($ch, CURLOPT_POST, true);  

  16.     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  

  17.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   

  18.     curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);  

  19.   

  20.     $response = curl_exec($ch);  

  21.   

  22.     if($error=curl_error($ch)){  

  23.         die($error);  

  24.     }  

  25.   

  26.     curl_close($ch);  

  27.   

  28.     return $response;  

  29.   

  30. }  

  31.   

  32. // 調用  

  33. $url = 'https://www.example.com/api/message.php';  

  34. $data = array('name'=>'fdipzone');  

  35. $header = array();  

  36.   

  37. $response = curl_https($url$data$header, 5);  

  38.   

  39. echo $response;  

  40. ?>  

相關文章
相關標籤/搜索