Search code examples
phperror-handlingfopen

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?


Solution

  • 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  
    }