Skip to content Skip to sidebar Skip to footer

File_get_contents Good Way To Handle Errors

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

Solution 1:

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);
?>

Solution 2:

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);

Solution 3:

You could do any of the following:

Set a global error handler (that will handle WARNINGs as well), for all of your unhandled exceptions: http://php.net/manual/en/function.set-error-handler.php

Or by checking the return value of the file_get_contents function (with the === operator, as it will return boolean false on failure), and then manage the error message accordingly, and disable the error reporting on the function by prepending a "@" like so:

$json = @file_get_contents("file", true);
if($json === false) {
// error handling
} else {
//do something with $json
}

Solution 4:

As a solution to your problem please try executing following code snippet

try  
{  
  $json = @file_get_contents("sidiowdiowjdiso", true); //getting the file contentif($json==false)
  {
     thrownewException( 'Something really gone wrong');  
  }
}  
catch (Exception$e)  
{  
  echo$e->getMessage();  
}  

Post a Comment for "File_get_contents Good Way To Handle Errors"