Saturday, November 14, 2015

PHP: fopen error handling

http://stackoverflow.com/questions/24753821/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?
shareimprove this question

    
i tried something like this if($fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb")){ throw this->createNotFoundException('No image found for id '.$team_id); } but it didnt worked. – humpdi Jul 15 '14 at 8:54
    
i did also tried try catch block, but didnt worked. the error was readable to the client. – humpdi Jul 15 '14 at 8:56
    
try { $fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb"); } catch(Exception $e) { throw $this->createNotFoundException('No image found for id '.$team_id); } – humpdi Jul 15 '14 at 8:58

3 Answers

up vote 5 down vote accepted
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  
    }
shareimprove this answer

    
thanks a lot dude, thats the point! :) – humpdi Jul 15 '14 at