Reputation: 4665
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 ?
Upvotes: 6
Views: 5840
Reputation: 11
You can use curl for avoid displaying php errors :
$externalUrl = ** your http request **
curl_setopt($curl, CURLOPT_URL, $externalUrl); // Set the URL
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36'); // Use your user agent
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set so curl_exec returns the result instead of outputting it.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // Bypass SSL Verifyers
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
$result = curl_exec($curl); // send request
$result = json_decode($result);
Upvotes: 1
Reputation: 15053
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() . ')';
}
Upvotes: 6
Reputation: 158060
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']);
}
}
Upvotes: 8
Reputation: 371
You can turn off warnings in PHP :
Turn off warnings and errors on PHP and MySQL
See in documentation:
https://www.php.net/manual/en/function.file-get-contents.php
Return Values: The function returns the read data or FALSE on failure.
or write @, before function, for avoid to see error:
@file_get_contents(...
Upvotes: 0
Reputation: 5901
This should work:
@file_get_contents("http://www.site.com");
The @
suppresses warnings and errors to be output by PHP. You will have to deal with an empty response yourself then.
Upvotes: 2