如何在php中利用curl获取https请求

这篇文章将为大家详细讲解有关如何在php中利用curl获取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  $data       要發送的數據
* @param Array  $header     请求时发送的header
* @param int    $timeout    超时时间,默认30s
*/ 
function curl_https($url, $data=array(), $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, http_build_query($data)); 
    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'; 
$data = array('name'=>'fdipzone'); 
$header = array(); 
 
$response = curl_https($url, $data, $header, 5); 
 
echo $response; 
?>

关于如何在php中利用curl获取https请求就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。