File_get_contents is a good way to handle errors

I am trying to process the file_get_contents method with an error, so even if the user enters the wrong website, it will echo an error message, not an unprofessional one

Warning: file_get_contents (sidiowdiowjdiso): could not open the stream: There is no such file or directory in C: \ xampp \ htdocs \ test.php on line 6

I thought that if I try and catch, he 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); } 
+6
source share
4 answers

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); ?> 
+9
source

file_get_contents do not throw an exception in the error, instead it returns false, so you can check if the return value is false:

 $json = file_get_contents("sidiowdiowjdiso", true); if ($json === false) { //There is an error opening the file } 

Thus, you will still receive a warning, if you want to remove it, you need to put @ in front of file_get_contents . (This is considered bad practice)

 $json = @file_get_contents("sidiowdiowjdiso", true); 
+7
source

You can do any of the following:

Install a global error handler (which will also handle warnings) 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, since it will return a boolean false if an error occurs), and then properly manage the error message and disable the function error report by adding "@" like this:

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

As a solution to your problem, try the following code snippet

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

All Articles