I succesfully fetch websites with
file_get_contents("http://www.site.com");
However, if the url doesn't exist, or not reachable, I am getting
Warning: file_get_contents(http://www.site.com) [function.file-get-contents]:
failed to open stream: operation failed in /home/track/public_html/site.php
on line 773
Is it possible to echo "Site not reachable";
instead of the error ?
You can use the silence operator @
together with $php_errormsg
:
if(@file_get_contents($url) === FALSE) {
die($php_errormsg);
}
Where the @
suppresses the error message, the message text will be available for output in $php_errormsg
But note that $php_errormsg
is disabled by default. You'll have to turn on track_errors
. So add at the top of your code:
ini_set('track_errors', 1);
However there is a way that does not depend on track errors:
if(@file_get_contents($url) === FALSE) {
$error = error_get_last();
if(!$error) {
die('An unknown error has occured');
} else {
die($error['message']);
}
}
I would perfer to trigger exceptions instead of error messages:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
// see http://php.net/manual/en/class.errorexception.php
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
Now you can catch the error like this:
try {
$content = file_get_contents($url);
} catch (ErrorException $ex) {
echo 'Site not reachable (' . $ex->getMessage() . ')';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With