How can I handle the warning of file_get_contents() function in PHP?


I wrote a PHP code like this

$content = file_get_content($site);
echo $content;

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

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

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

8/29/2013 1:05:47 PM

Accepted Answer

Step 1: check the return code: if($content === FALSE) { // handle error here... }

Step 2: suppress the warning by putting an error control operator (i.e. @) in front of the call to file_get_contents(): $content = @file_get_contents($site);

4/12/2017 1:57:59 PM

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

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

try {
catch (Exception $e) {
    echo $e->getMessage();


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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow