views:

4453

answers:

7

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 this warning

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

i try ( try and Catch ) but it didn't work .

+6  A: 

You can prepend an @: $content = @file_get_contents($site);

This will supress any warning - use sparingly!. See Error Control Operators

Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."

Greg
+9  A: 

Step 1: check the return code: if ($content==FALSE) { handle error here... } Step 2: suppress the warning by putting an @ in front of the file_get_content: $content = @file_get_content($site);

Roel
+1  A: 

As RoBorg already suggested, you can supress errors by prepending an @. The real solution is to actually validate your input and act accordingly; assuming that a string is formatted correctly could cause trouble and is something you should generally avoid.

Use something like

if (preg_match('/^https?:\/\/.+/', $site))
{
    $contents = file_get_contents($site);
}
else
{
    // error handling of some sort, or alternative solution / input checking
}
Aron Rotteveel
What if the site is a valid URL but down for maintenance...your code above will only work when the site is up.
joedevon
A: 

Or you can prepend the http:// to links which do not have it.

orlandu63
+2  A: 

The best thing would be to set your own error and exception handlers which will do something usefull like logging it in a file or emailing critical ones. http://www.php.net/set_error_handler

+4  A: 

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";
}
+1  A: 

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(
    create_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.

enobrev