I am trying to error handle the file_get_contents method so even if the user enters an incorrect website it will echo an error message rather then the unprofessional
Warning: file_get_contents(sidiowdiowjdiso): failed to open stream: No such file or directory in C:\xampp\htdocs\test.php on line 6
I thought if i make a try and catch it will be able to catch the error but that did not work.
try
{
$json = file_get_contents("sidiowdiowjdiso", true); //getting the file content
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string.
The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .
They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string.
Try cURL with curl_error instead of file_get_contents:
<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = '';
if( ($json = curl_exec($ch) ) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
}
// Close handle
curl_close($ch);
?>
file_get_contents
do not throw an exception in error, instead it returns false, so you can check if the returned value is false:
$json = file_get_contents("sidiowdiowjdiso", true);
if ($json === false) {
//There is an error opening the file
}
This way you still get the warning, if you want to remove it, you need to put an @
in front of file_get_contents
. (This is considered a bad practice)
$json = @file_get_contents("sidiowdiowjdiso", true);
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