包子

木森技术分享

路漫漫其修远兮,吾将上下而求索。

您现在的位置是:网站首页 > PHP

file_get_contents() 访问https链接报错解决方案

2024-02-23 15:42:21233

        原因:

        服务器上未能正确配置好https证书,所以出现了错误。

        解决方法:

        方法1:

        1.下载证书,http://curl.haxx.se/ca/cacert.pem

        2.证书上传到服务器,并记录好上传的路径

        3.打开php的配置文件,php.ini

        4.修改openssl.cafile的配置的值为上传的证书地址即可

        例:

openssl.cafile = "/etc/ssl/certs/cacert.pem"

    5.重启php即可

    方法2:

    直接对file_get_contents函数进行设置,让file_get_contents函数跳过https验证,暂时解决问题

    例:

$url = 'url';
$arrContextOptions=array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
        "allow_self_signed"=>true,
    ),
);
$response = file_get_contents($url, false, stream_context_create($arrContextOptions));

    方法3:

    使用curl来替代file_get_contents函数来使用!

    例:

$url = 'url';
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
var_dump(getSSLPage($url));