How can I handle the warning of file_get_contents&

2019-01-02 17:03发布

I wrote a PHP code like this

$site="http://www.google.com";
$content = file_get_content($site);
echo $content;

But when I remove "http://" from $site I get the following warning:

Warning: file_get_contents(www.google.com) [function.file-get-contents]: failed to open stream:

I tried try and catch but it didn't work.

16条回答
高级女魔头
2楼-- · 2019-01-02 17:30

Here's how I did it... No need for try-catch block... The best solution is always the simplest... Enjoy!

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
} 
查看更多
梦寄多情
3楼-- · 2019-01-02 17:31

You can also set your error handler as an anonymous function that calls an Exception and use a try / catch on that exception.

set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, $severity, $severity, $file, $line);
    }
);

try {
    file_get_contents('www.google.com');
}
catch (Exception $e) {
    echo $e->getMessage();
}

restore_error_handler();

Seems like a lot of code to catch one little error, but if you're using exceptions throughout your app, you would only need to do this once, way at the top (in an included config file, for instance), and it will convert all your errors to Exceptions throughout.

查看更多
临风纵饮
4楼-- · 2019-01-02 17:31

You should use file_exists() function before to use file_get_contents(). With this way you'll avoid the php warning.

$file = "path/to/file";

if(file_exists($file)){
  $content = file_get_contents($file);
}
查看更多
无色无味的生活
5楼-- · 2019-01-02 17:31

You should also set the

allow_url_use = On 

in your php.ini to stop receiving warnings.

查看更多
登录 后发表回答