[PHP自动化-进阶]003.CURL处理Https请求访问

引言:继前文《模拟登陆并采集数据》,《模拟登陆带有验证码的网站》,你们对CURL基本上已经有了认识,这一讲简单的说一下请求Https。php

在不少的站点,如TalkingData, BaiDu等等,一些请求协议都是走SSL,大白话来讲就是Https,这种协议在模拟CURL时可能会出现请求不成功等等的问题。html

下面为你们讲一下解决方案。算法

这一讲很简单,但能说明问题……。api

 

异常提示
curl


大多数异常信息提示以下:证书验证失败。post

SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed 网站

 

切入主题ui


解决方法,在curl请求时,加入加密

// 跳过证书检查  
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 从证书中检查SSL加密算法是否存在  
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  

 

 curl https post请求封装代码代码url

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

 

未完待续……。

 

 

 

本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(做者官方网站: 宝宝巴士 
转载自【宝宝巴士SuperDo团队】 原文连接: http://www.cnblogs.com/superdo/p/4792496.html

相关文章
相关标签/搜索