2014-07-15 169 views
6

我取一个文件PHP:FOPEN错误处理

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

,然后的方法进行回作为图像。但是,当的fopen()失败,因为该文件不存在,它抛出一个错误:

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

这回来为JSON,效果显着。

现在的问题是:如何捕获错误并防止该方法直接向客户端抛出此错误?

+0

我想是这样的'如果($计划生育=的fopen( '上传/团队/ IMG /'.$ TEAM_ID。' 巴 ' “RB”)){抛出这个 - > createNotFoundException(' 不image for found for id'。$ team_id); }' 但它没有奏效。 – humpdi

+0

我也曾尝试尝试catch块,但没有工作。该错误对客户端可读。 – humpdi

+0

'try {$ fp = fopen('uploads/Team/img /'。team_id。'。png',“rb”); } catch(Exception $ e){throw $ this-> createNotFoundException('没有找到id的图像。$ team_id); }' – humpdi

回答

23

你应该首先通过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 
    } 

或简单的解决方案,而例外:

$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 
    } 
+0

非常感谢你的家伙,这就是要点! :) – humpdi

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

错误是明确的:你已经把错误的目录,你可以试试你whant什么,但它会无法正常工作。你可以把它与这方面的工作:

  1. 把你的文件,并把它放在你的PHP文件 的同一文件夹(你可以以后移动它不用担心,这是你的错误) 或文件夹脚本的“高”(只是没有外面您的www 文件夹)
  2. 变化则fopen到('./$team_id.'png',"rb");
  3. 重新运行脚本文件

不要忘记:你可以” t访问一个不存在于你的文件中的文件ww“文件夹 (他没有找到你的文件,因为他给了你她的名字:这个名字来自$ team_id变量)

1

您可以调用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); 
}