问题表现
file_get_contents 读取一个正常的 https 的url时,返回 false
打开报错
错误提示
- PHP Warning: file_get_contents(https://graph.qq.com/): failed to open stream: No such file or directory in Command line code on line 1
复制代码
原因
php 所在的环境没有打开 openssl 的支持
解决方法
一、在 windows 下
只要打开相应的 dll 即可,就是找到 php.ini
把
- ;extension=php_openssl.dll
复制代码
前的分号去掉,重启 web 服务。
二、在 linux 下
重新编译 php,加入参数
或者单独编译 openssl,然后在 php.ini 里添加加载该模块
========
如果没有条件修改环境,并且服务器支持 curl,可以使用以下函数替换 file_get_contents
- function _file_get_contents($url) {
- if (!function_exists('curl_init')) {
- return false;
- }
- $timeout = 10;
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
- $contents = curl_exec($ch);
- curl_close($ch);
- return $contents;
- }
复制代码 |