如何修复 php 警告:file_get_contents?failed to open stream: HTTP request failed
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12791974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix php Warning: file_get_contents?failed to open stream: HTTP request failed
提问by u1334703
How to fix php Warning: file_get_contents?
如何修复 php 警告:file_get_contents?
Warning: file_get_contents(http://192.168.1.254:9999/api/p/internal/ucenter/login?loginName=test102&password=111111) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /Applications/XAMPP/xamppfiles/htdocs/PHP_test/index.php on line 49
Here is code related to $files:
这是与 $files 相关的代码:
<?php
$loginNames="test102";
$passwords="111111";
$apiUrl = "http://192.168.1.254:9999/api/p/internal/ucenter/login?loginName=".$loginNames."&password=".$passwords;
$callback = file_get_contents($apiUrl);
print_r($callback);
//echo $callback;
?>
回答by Ja?ck
If this shows in your page, there's something wrong with your display_errorssetting.
如果这显示在您的页面中,则说明您的display_errors设置有问题。
Ideally, display_errorsshould be Offfor production machines and you should handle errors by yourself using set_error_handler().
理想情况下,display_errors应该Off用于生产机器,您应该使用set_error_handler().
See also: Error logging, in a smooth way
另请参阅:错误记录,以流畅的方式
This particular warning can't be stopped unless you make sure the page exists. However, used in isolation, you can use the muffle operatorto prevent the warning from appearing:
除非您确保该页面存在,否则无法停止此特定警告。但是,单独使用时,您可以使用muffle 运算符来防止出现警告:
if (false !== ($contents = @file_get_contents('...'))) {
// all good
} else {
// error happened
}
Note that this will still call your custom error handler
请注意,这仍会调用您的自定义错误处理程序
回答by Ronak Patel
I have better option for you.
我有更好的选择给你。
Avoid file_get_contents, user cURL.
避免file_get_contents,用户 cURL。
Let me show you one example:
让我给你看一个例子:
$url = 'http://www.yoururl.com';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$data = curl_exec($curl);
curl_close($curl);
Note: Is you feel encoding problem add this: curl_setopt($curl, CURLOPT_ENCODING ,"");
注意:您是否觉得编码有问题,请添加以下内容: curl_setopt($curl, CURLOPT_ENCODING ,"");
Thanks.
谢谢。
回答by Kodomo
I suggest try to check if url exist before you call file_get_contents. You can ref page How can I check if a URL exists via PHP?
我建议在调用 file_get_contents 之前尝试检查 url 是否存在。您可以参考页面如何通过 PHP 检查 URL 是否存在?

