php使用curl访问https示例

180it 2019-12-23 PM 2589℃ 0条

今日在做一个项目,需要curl获取第三方的API,对方的API是https方式的。
之前使用curl能获取http请求,但今天获取https请求时,返回的内容总是为空,查阅资料后发现用curl访问https需要添加以下两行代码:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
封装成一个函数如下:

/** 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, 2); // 从证书中检查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;   
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php使用curl访问https示例