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. ?>  

相关文章
相关标签/搜索