鍍金池/ 問答/PHP  C  C++/ php的curl擴展無法發(fā)起https請求

php的curl擴展無法發(fā)起https請求

很奇怪的是,file_get_content函數(shù)可以對https地址發(fā)起請求并且收到響應(yīng)報文,但是curl就不可以,這是什么原因呢?我已經(jīng)安裝了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

回答
編輯回答
傲寒

CURLOPT_SSL_VERIFYPEER 新版php中默認是2

2018年1月13日 02:12
編輯回答
執(zhí)念

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//這個是重點
加上這句就可以了,跳過https證書驗證

2017年8月14日 17:40
編輯回答
純妹
2018年3月20日 05:04
編輯回答
撥弦

看 curlerror的信息

2017年1月11日 18:30
編輯回答
執(zhí)念
<?php
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

雖然加上上面一行,就可以讓curl忽略https認證,可以保證你能夠發(fā)出去請求
但是,十分不建議你這么操作,因為你一旦忽略掉https認證,你就無法保證你服務(wù)器發(fā)起的請求得到的是正常,沒有被劫持和替換的響應(yīng)。

更加推薦的的方式
項目中先使用 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...

2017年5月15日 11:53