这篇文章主要介绍了 php 使用 curl 获取 https 请求的方法, 涉及 curl 针对 https 请求的操作技巧, 非常具有实用价值, 需要的朋友可以参考下
本文实例讲述了 php 使用 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 $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;
- ?>
来源: https://www.php1.cn/detail/php-6a54793ba1.html