PHP:fopen错误处理 [英] PHP: fopen error handling
本文介绍了PHP:fopen错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用
$fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb");
$str = stream_get_contents($fp);
fclose($fp);
然后该方法将其作为图像返回。但是当fopen()失败时,因为文件不存在,它会引发错误:
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:\...
显然,这是回到json。
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?
推荐答案
您应该先测试一个文件的存在通过file_exists()。
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
}
这篇关于PHP:fopen错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文