关于php函数 file_get_contents返回false的几种解决方法

请求腾讯地图的API时 用file_get_contents请求直接返回false 注意:我在本地请求的时候是成功的 最后冥思苦想+各种测试 发现file_get_contents 不支持https的请求**(我用的php版本5.6)** ,最后查阅了一些资料 现整理如下

	1,下载https证书到服务器
		服务器 下载这个证书,http://curl.haxx.se/ca/cacert.pem
		php.ini 配置
		openssl.cafile = "/etc/ssl/certs/cacert.pem"//你实际下载证书的路径
		重启 php 即可
2,使用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"));

还有一种post
function getSSLPage($url) {
    
    
$post    = array(
	'字段'    => '值',
);
$url    = '对应url地址';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据不直接输出
curl_setopt($ch, CURLOPT_POST, 1);      //发送POST类型数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //POST数据,$post可以是数组,也可以是拼接
$content = curl_exec($ch);          //执行并存储结果
curl_close($ch);  

}
	?>

	引用:https://stackoverflow.com/questions/14078182/openssl-file-get-contents-failed-to-enable-crypto
3,使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));

开发中建议使用cURL 函数替代file_get_contents()函数。
转载来自:https://www.cnblogs.com/wenzheshen/p/11179533.html

猜你喜欢

转载自blog.csdn.net/weixin_43944691/article/details/104900888