I am trying to fetch an image using file_get_contents
function but it gives an error. To handle the error I am using try catch block but it does not catch the error and fails.
My code:
try {
$url = 'http://wxdex.ocm/pdd.jpg'; //dummy url
$file_content = file_get_contents($url);
}
catch(Exception $e) {
echo 'Error Caught';
}
Error:
Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: No such host is known
Warning: file_get_contents(http://wxdex.ocm/pdd.jpg): failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known.
NOTE:: I am able to fetch any other valid image url on remote.
try/catch
doesn't work because a warning
is not an exception
.
You can try this code so you can catch warnings as well.
//set your own error handler before the call
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);
try {
$url = 'http://wxdex.ocm/pdd.jpg';
$file_content = file_get_contents($url);
} catch (Exception $e) {
echo 'Error Caught';
}
//restore the previous error handler
restore_error_handler();
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