curl 獲取 https 請求方法
來源:程序員人生 發布時間:2014-10-06 08:00:00 閱讀次數:2516次
curl 獲取 https 請求方法
今日在做一個項目,需要curl獲取第三方的API,對方的API是https方式的。
之前使用curl能獲取http請求,但今天獲取https請求時,出現了以下的錯誤提示:證書驗證失敗。
SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
解決方法,在curl請求時,加入
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳過證書檢查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 從證書中檢查SSL加密算法是否存在
curl https請求代碼
<?php
/** curl 獲取 https 請求
* @param String $url 請求的url
* @param Array $header 請求時發送的header
* @param int $timeout 超時時間,默認30s
*/
function curl_https($url, $header=array(), $timeout=30){
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳過證書檢查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 從證書中檢查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$response = curl_exec($ch);
if($error=curl_error($ch)){
die($error);
}
curl_close($ch);
return $response;
}
// 調用
$url = 'https://www.example.com/api/message.php';
$header = array('content-type:application/json');
$response = curl_https($url, $header, 5);
echo $response;
?>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈