PHP:fopen错误处理

hum*_*pdi 19 php error-handling fopen

我用文件获取文件

$fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb");
$str = stream_get_contents($fp);
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

然后该方法将其作为图像返回.但是当fopen()失败时,因为该文件不存在,它会抛出一个错误:

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

显然,这将以json的形式回归.

问题现在是:我如何捕获错误并阻止该方法直接将此错误抛给客户端?

小智 39

您应该首先通过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
    } 
Run Code Online (Sandbox Code Playgroud)

或简单的解决方案,无例外

    $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  
    }
Run Code Online (Sandbox Code Playgroud)

  • FWIW 如果偶然在“fopen”之间的纳秒内删除“$fileName”,这仍然会引发OP的原始警告。这在高流量网站上主要是可复制的。可能是我可以沉默任何东西的唯一场景: `$fp = @fopen(....); 如果 (!$fp) 抛出......` (2认同)

小智 5

您可以在调用fopen()之前使用file_exists()函数。

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);
}
Run Code Online (Sandbox Code Playgroud)