如何修复PHP警告:file_get_contents?failed to open stream: HTTP request failed

4

如何修复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); - inhan
如果您在浏览器中打开该URL,会发生什么?您被重定向了吗?尝试使用CURL并查看标头返回的内容。 - shapeshifter
请参考此链接中的 CURL 代码,以上传远程 URL 到服务器。 - shapeshifter
使用CURL(http://php.net/manual/en/book.curl.php) - Nabi K.A.Z.
3个回答

12
如果这段文字显示在您的页面上,那么您的display_errors设置可能有问题。
理想情况下,生产环境中的display_errors应该设置为Off,并且您应该使用set_error_handler()自行处理错误。
另请参阅:以平滑的方式记录错误日志 除非确保页面存在,否则无法阻止此特定警告。但是,如果单独使用,您可以使用抑制运算符来防止警告出现。
if (false !== ($contents = @file_get_contents('...'))) {
    // all good
} else {
    // error happened
}

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

1
我有更好的选择给你。
避免使用 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 ,""); 谢谢。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接