PHP: fopen error handling

后端 未结 4 855
天涯浪人
天涯浪人 2021-02-05 03:33

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

4条回答
  •  我在风中等你
    2021-02-05 04:35

    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  
    }
    

提交回复
热议问题