在php中使用curl庫訪問https,具體方法如下:
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;
}