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

发布时间 2023-11-02 17:12:42作者: 郭德纲又打人了嘿

在调试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 的配置的值为上传的证书地址即可

例如:

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

(5)、重启 php 即可

 

方法2:

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

例:

 1 # feiniaomy.com 飞鸟慕鱼博客
 2 $url = '请求地址';
 3 $arrContextOptions=array(
 4     "ssl"=>array(
 5         "verify_peer"=>false,
 6         "verify_peer_name"=>false,
 7         "allow_self_signed"=>true,
 8     ),
 9 );
10 $response = file_get_contents($url, false, stream_context_create($arrContextOptions));

 

方法3:

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

例:

 1 # feiniaomy.com 飞鸟慕鱼博客
 2 $url = '请求地址';
 3 function getSSLPage($url) {
 4     $ch = curl_init();
 5     curl_setopt($ch, CURLOPT_HEADER, false);
 6     curl_setopt($ch, CURLOPT_URL, $url);
 7     curl_setopt($ch, CURLOPT_SSLVERSION,3); 
 8     $result = curl_exec($ch);
 9     curl_close($ch);
10     return $result;
11 }
12 var_dump(getSSLPage($url));

来源:https://www.feiniaomy.com/post/1021.html