PHP: fopen error handling

2019-03-24 05:45发布

问题:

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?

回答1:

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  
    }


回答2:

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);
}


回答3:

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

the error is clear: you've put the wrong directory, you can try what you whant but it'll not work. you can make it work with this:

  1. take your file and put it in the same folder of your php file (you'll be able to move it after don't worry, it's about your error) or on a folder "higher" of your script (just not outside of your www folder)
  2. change the fopen to ('./$team_id.'png',"rb");
  3. rerun your script file

don't forget this : you can't access a file that is'nt in your "www" folder (he doesn't found your file because he give you her name: the name come from the $team_id variable)