PHP: fopen error handling

I am extracting a file using

$fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb"); $str = stream_get_contents($fp); fclose($fp); 

and then the method returns it as an image. But when fopen () fails because the file does not exist, it throws an error:

 [{"message":"Warning: fopen(uploads\/Team\/img\/1.png): failed to open stream: No such file or directory in C:\... 

This will return as json, obviously.

The question now is: how can I catch an error and prevent the method from throwing this error directly to the client?

+6
source share
3 answers

You must first check for the existence of file_exists ().

  try { $fileName = 'uploads/Team/img/'.$team_id.'.png'; if ( !file_exists($fileName) ) { throw new Exception('File not found.'); } $fp = fopen($fileName, "rb"); if ( !$fp ) { throw new Exception('File open failed.'); } $str = stream_get_contents($fp); fclose($fp); // send success JSON } catch ( Exception $e ) { // send error message if you can } 

or a simple solution with no exceptions:

  $fileName = 'uploads/Team/img/'.$team_id.'.png'; if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false ) { $str = stream_get_contents($fp); fclose($fp); // send success JSON } else { // send error message if you can } 
+23
source

You can use the file_exists () function before calling fopen () .

 if(file_exists('uploads/Team/img/'.$team_id.'.png') { $fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb"); $str = stream_get_contents($fp); fclose($fp); } 
+1
source
 [{"message":"Warning: fopen(uploads\/Team\/img\/1.png): failed to open stream: No such file or directory in C:\... 

the error is clear: you put the wrong directory, you can try what you want, but it will not work. you can make it work with this:

  • take the file and put it in the same folder of your php file (you can move it after you don’t worry, it’s about your mistake) or in the β€œabove” folder of your script (just not outside your www folder)
  • change fopen to ('./$team_id.'png',"rb");
  • reload script file

do not forget: you cannot access the file located in your www folder (he did not find your file because he gave you his name: the name is taken from the $ team_id variable)

0
source

Source: https://habr.com/ru/post/972237/


All Articles