18910140161

php file_get_contents(): SSL operation failed with code 1. OpenSSL Error message.....

顺晟科技

2022-10-19 09:13:32

44

在调试php脚本代码时,发现使用 file_get_contents() 函数请求HTTPS的网址链接时出现了报错,其报错代码如下面所示“file_get_contents(): SSL operation failed with code 1. OpenSSL Error message...”百度查了一下原因与解决方法,下面就来分享一下。

原因:

服务器上未能正确配置好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验证,暂时解决问题

例:

# feiniaomy.com 顺晟科技博客
$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 函数来使用!

例:

# feiniaomy.com 顺晟科技博客
$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));
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航