Why doesn't the following print "Error!" but only prints the 'failed to open stream...' warning?
try {
file_get_contents('www.invalid-url.com');
} catch (Exception $e) {
echo 'Error!';
}
Why doesn't the following print "Error!" but only prints the 'failed to open stream...' warning?
try {
file_get_contents('www.invalid-url.com');
} catch (Exception $e) {
echo 'Error!';
}
It returns FALSE on error, it doesn't throw and exception.
So you could use @ to suppress the warning (if required) and check the result to see if there was an error
$content = @file_get_contents('http://www.example.com');
if ( $content === FALSE ){
echo "Error!";
}
file_get_contents doesn't throw an exception, but returns FALSE if it fails. file_get_contents is a highly primitive function. If you want more advanced feedback, use cURL.
E.g. something like this:
$curl = curl_init('your URL here');
// Return the output to a string instead of the screen with CURLOPT_RETURNTRANSFER
curl_setopt($pCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($pCurl, CURLOPT_TIMEOUT, 10);
$content = curl_exec($curl);
$info = curl_getinfo($curl);
if($info['http_code'] === 200)
{
return $content;
}
PHP doesn't use exceptions by default but an error message mechanism. If you want exceptions you could use a custom error handler like in http://php.net/manual/en/class.errorexception.php
The more PHP'ish way would be to shutdown the error message and check the return code. Shutting down can be done globally by error_reporting(0);
or ini_set('display_errors', false);
or using the @
operator.
<?php
if (!@file_get_contents(....)) {
echo "ERROR";
}
?>