Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: fopen error handling

I do fetch a file with

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

and then the method gives it back as image. But when fopen() fails, because the file did not exists, it throws an error:

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

This is coming back as json, obviously.

The Question is now: How can i catch the error and prevent the method from throwing this error directly to the client?

like image 451
Fabian Avatar asked Jul 15 '14 08:07

Fabian


People also ask

How do I know if fopen is working in PHP?

You can use the file_exists() function before calling fopen(). Show activity on this post. [{"message":"Warning: fopen(uploads\/Team\/img\/1.

What does fopen () function do in PHP?

The fopen() function opens a file or URL.

How do you find the fopen error?

The fopen() function will fail if: [EACCES] Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created. [EINTR]

When using the fopen () function to open a file in PHP What made should you use for appending data to a file?

One can append some specific data into a specific file just by using a+ or a mode in the fopen() function. The PHP Append to file is done just by using the fwrite() function of PHP Programming Language.


1 Answers

You should first test the existence of a file by 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 simple solution without 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   } 
like image 104
Cendak Avatar answered Sep 25 '22 23:09

Cendak