Search code examples
phpfile-get-contents

How to fix php Warning: file_get_contents?failed to open stream: HTTP request failed


How to fix php Warning: 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:

<?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;
?>

Solution

  • If this shows in your page, there's something wrong with your display_errors setting.

    Ideally, display_errors should be Off for production machines and you should handle errors by yourself using 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 operator to prevent the warning from appearing:

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

    Note that this will still call your custom error handler