【问题标题】:How to fix php Warning: file_get_contents?failed to open stream: HTTP request failed如何修复 php 警告:file_get_contents?未能打开流:HTTP 请求失败
【发布时间】:2012-10-09 02:15:56
【问题描述】:

如何修复 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

这里是与 $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;
?>

【问题讨论】:

  • 你试过像$callback = @file_get_contents($apiUrl); if($callback !== false) print_r($callback);一样吗?
  • 如果您在浏览器中访问该 URL 会发生什么?你重定向了吗?尝试使用 CURL 并查看标头返回的内容。
  • stackoverflow.com/questions/12489499/… 用于类似的 CURL 代码。

标签: php file-get-contents


【解决方案1】:

如果这显示在您的页面中,则说明您的 display_errors 设置有问题。

理想情况下,display_errors 对于生产机器应该是Off,您应该使用set_error_handler() 自行处理错误。

另见:Error logging, in a smooth way

除非您确定该页面存在,否则无法停止此特定警告。但是,单独使用,您可以使用muffle operator 来防止出现警告:

if (false !== ($contents = @file_get_contents('...'))) {
    // all good
} else {
    // error happened
}

请注意,这仍会调用您的自定义错误处理程序

【讨论】:

    【解决方案2】:

    我有更好的选择。

    避免file_get_contents,用户cURL

    让我举一个例子:

    $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);
    

    注意:是不是觉得编码有问题加这个:curl_setopt($curl, CURLOPT_ENCODING ,"");

    谢谢。

    【讨论】:

      【解决方案3】:

      我建议在调用 file_get_contents 之前尝试检查 url 是否存在。 您可以参考页面How can I check if a URL exists via PHP?

      【讨论】:

        猜你喜欢
        • 2015-05-13
        • 2012-07-26
        • 1970-01-01
        • 2010-10-16
        • 2014-09-25
        • 1970-01-01
        • 2016-06-02
        • 2016-02-16
        • 1970-01-01
        相关资源
        最近更新 更多