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?
You can use the file_exists() function before calling fopen(). Show activity on this post. [{"message":"Warning: fopen(uploads\/Team\/img\/1.
The fopen() function opens a file or URL.
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]
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.
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 }
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