//今天写一个采集页面,用PHP CURL https 竟然报错,搜集了一些资料,完成了 PHP CURL 获取HTTPS网页源码的函数。
function GetHtml($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.baidu.com/');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; GTB6.6; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // ssl 访问核心参数
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // ssl 访问核心参数
$code = curl_exec($ch);
curl_close($ch);
if (empty($code) or stristr($code, '403 Forbidden ') or stristr($code, "
nginx") or stristr($code, "Error ") or stristr($code, "无法找到该页 ")) {
exit();
} else {
return $code;
}
}
function curlPost($url, $data, $timeout = 30) {
$ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;
$ch = curl_init();
$opt = array(
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_POSTFIELDS => (array) $data,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => $timeout,
);
if ($ssl) {
$opt[CURLOPT_SSL_VERIFYHOST] = 1;
$opt[CURLOPT_SSL_VERIFYPEER] = FALSE;
}
curl_setopt_array($ch, $opt);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$data = curlPost('https://www.111cn.net', array('p' => 'hello'));
echo ($data);
/**
* 为方便说明,先上代码吧~ 这是今天重新封装的一个函数代码如下
* curl POST
* @param string url
* @param array 数据
* @param int 请求超时时间
* @param bool HTTPS时是否进行严格认证
* @return string
*/
function curlPost($url, $data = array(), $timeout = 30, $CA = true) {
$cacert = getcwd() . '/cacert.pem'; //CA根证书
$SSL = substr($url, 0, 8) == "https://" ? true : false;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout - 2);
if ($SSL && $CA) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 只信任CA颁布的证书
curl_setopt($ch, CURLOPT_CAINFO, $cacert); // CA根证书(用来验证的网站证书是否是CA颁布)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名,并且是否与提供的主机名匹配
} else if ($SSL && !$CA) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); //避免data数据过长问题
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); //data with URLEncode
$ret = curl_exec($ch);
//var_dump(curl_error($ch)); //查看报错信息
curl_close($ch);
return $ret;
}
来自:http://www.526net.com/blog/qianduan/353.html