file_get_contents是否会正常失败? [英] Will file_get_contents fail gracefully?
问题描述
我需要 file_get_contents
才能容错,例如,如果馈给它的$url
返回 404 ,请在回显警告之前告诉我有关它的信息.能做到吗?
I need file_get_contents
to be fault tolerant, as in, if the $url
fed to it returns a 404, to tell me about it before it echos out a warning. Can this be done?
推荐答案
任何使用HTTP包装器访问远程文件的函数,就好像它是本地的一样,都会自动生成一个名为
Any function that uses the HTTP wrapper to access a remote file as if it were local will automatically generate a local variable named $http_response_header
in the local scope. You can access that variable to find information about what happened in a call to fopen
, file_get_contents
... on a remote file.
您可以使用@
:@file_get_contents
禁止显示警告.
You can suppress the warning using @
: @file_get_contents
.
如果您不关心错误是什么,可以使用@file_get_contents
并将结果与false
进行比较:
If you don't care about what the error was, you can use @file_get_contents
and compare the result to false
:
$content = @file_get_contents(url);
if ($content === false) { /* failure */ } else { /* success */ }
这篇关于file_get_contents是否会正常失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!