php的curl扩展无法发起https请求

很奇怪的是,file_get_content函数可以对https地址发起请求并且收到响应报文,但是curl就不可以,这是什么原因呢?我已经安装了openssl扩展。

function fetch($url, $cookie=null, $postdata=null, $headers=null){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    echo "$url\n";
    if (!is_null($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    if (!is_null($postdata)) curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    if (!is_null($cookie)) curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $re = curl_exec($ch);
    curl_close($ch);
    return $re;
}

echo fetch("http://baidu.com"); // 有输出
echo fetch("https://baidu.com"); // 无输出
Administrator@changwei MINGW64 /d/www/test
$ php ./test.php
http://baidu.com
<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>

Administrator@changwei MINGW64 /d/www/test
$ php ./test.php
https://baidu.com
$ php -m
[PHP Modules]
bcmath
bz2
calendar
Core
ctype
curl
date
dom
ereg
fileinfo
filter
ftp
gd
hash
iconv
json
libxml
mbstring
mcrypt
mhash
mongo
mysql
mysqli
mysqlnd
odbc
openssl
pcre
PDO
pdo_mysql
pdo_sqlite
phalcon
Phar
redis
Reflection
session
SimpleXML
SPL
sqlite3
standard
tokenizer
wddx
xdebug
xml
xmlreader
xmlwriter
xsl
zip
zlib

[Zend Modules]
Xdebug

阅读 4.6k
5 个回答

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点
加上这句就可以了,跳过https证书验证

<?php
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

虽然加上上面一行,就可以让curl忽略https认证,可以保证你能够发出去请求
但是,十分不建议你这么操作,因为你一旦忽略掉https认证,你就无法保证你服务器发起的请求得到的是正常,没有被劫持和替换的响应。

更加推荐的的方式
项目中先使用 composer 安装上 paragonie/certainty 这个包
然后

<?php
use ParagonIE\Certainty\RemoteFetch;

/* ~8<~8<~8<~8<~8<~8<~8<~8<~ - S N I P - ~8<~8<~8<~8<~8<~8<~8<~8<~ */

$ch = curl_init();

/* ~8<~8<~8<~8<~8<~8<~8<~8<~ - S N I P - ~8<~8<~8<~8<~8<~8<~8<~8<~ */

$latestBundle = (new RemoteFetch())->getLatestBundle();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, $latestBundle->getFilePath());

/* ~8<~8<~8<~8<~8<~8<~8<~8<~ - S N I P - ~8<~8<~8<~8<~8<~8<~8<~8<~ */
$response = curl_exec($ch);

参考下文:
https://paragonie.com/blog/20...

看 curlerror的信息

CURLOPT_SSL_VERIFYPEER 新版php中默认是2

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题