PHP函数file_get_contents()使用 https 协议时报错:SSL operation failed

风雪飞雨 阅读:203 2025-11-18 22:10:05 评论:0

file_get_contents() 函数是用于将文件的内容读入到一个字符串中,是读取文件内容常用的函数之一。

但是有时在服务器上使用file_get_contents() 函数请求https 协议的url文件时会报错误,无法正确读取文件内容,

查看log日志,日志内容类似如下:

PHP Warning:  file_get_contents(): Failed to enable crypto in ......
PHP Warning:  file_get_contents......: failedream: operation failed in ......
PHP Warning:  file_get_contents(): SSL operatwith code 1. OpenSSL Error messages:error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verin ......

原因:

服务器未正确配置好https证书

解决方法:(三种解决方法)

方法一:

下载https证书到服务器

服务器 下载这个证书,http://curl.haxx.se/ca/cacert.pem
php.ini 配置
openssl.cafile = "/etc/ssl/certs/cacert.pem"//你实际下载证书的路径
重启 php 即可

 

方法二:

使用cURL 函数处理 https 的参数,获取文件内容

<?php
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("https://xxx.xxx.xxx"));
?>

方法三:

使file_get_contents()函数跳过https验证

$stream_opts = [
    "ssl" => [
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ]
]; 

$response = file_get_contents("https://xxx.xxx.xxx",false, stream_context_create($stream_opts));


声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
排行榜