温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

file_get_contents返回为空或函数不可用的解决方案

发布时间:2021-07-23 13:56:55 来源:亿速云 阅读:637 作者:chen 栏目:开发技术

本篇内容介绍了“file_get_contents返回为空或函数不可用的解决方案”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

如果你使用file_get_contents获取远程文件内容返回为空或提示该函数不可用,也许本文能帮到你!
使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini,设置allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。如果你使用的是虚拟主机可以考虑用curl函数来代替。
curl函数的使用示例:

复制代码 代码如下:


$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, ‘https://www.jb51.net');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);


利用function_exists函数来判断php是否支持file_get_contents,否则用curl函数来代替。
PS
1、如果你的主机服务商把curl也关闭了,那你还是换个主机商吧!
2、allow_url_fopen设为off,并不代表你的主机不支持file_get_content函数。只是不能打开远程文件而已。function_exists(‘file_get_contents')返回的是true。所以网上流传的《file_get_contents函数不可用的解决方法》还是不能解决问题。
错误代码:

复制代码 代码如下:


if (function_exists(‘file_get_contents')) {
$file_contents = @file_get_contents($url);
}else{
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}


应改为:

复制代码 代码如下:


if (function_exists(‘file_get_contents')) {//判断是否支持file_get_contents
$file_contents = @file_get_contents($url);
}
if ($file_contents == ”) {//判断$file_contents是否为空
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}


最终代码:

复制代码 代码如下:


function file_get_content($url) {
if (function_exists(‘file_get_contents')) {
$file_contents = @file_get_contents($url);
}
if ($file_contents == ”) {
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
}


用法:
echo file_get_content(‘https://www.jb51.net');

“file_get_contents返回为空或函数不可用的解决方案”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI