当getimagesize找不到文件时处理错误 [英] Handle error when getimagesize can't find a file

查看:384
本文介绍了当getimagesize找不到文件时处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试getimagesize($img)并且图像不存在时,出现错误.我不想先检查文件是否存在,只处理错误.

when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.

我不确定try catch的工作方式,但是我想做类似的事情:

I'm not sure how try catch works, but I want to do something like:

try: getimagesize($img) $works = true
catch: $works = flase

推荐答案

就像您说的那样,如果将其用于不存在的文件,则getimagesize会生成警告:

Like you said, if used on a non-existing file, getimagesize generates a warning :

此代码:

if ($data = getimagesize('not-existing.png')) {
    echo "OK";
} else {
    echo "NOT OK";
}

会为您带来

Warning: getimagesize(not-existing.png) [function.getimagesize]: 
  failed to open stream: No such file or directory 


一种解决方案是使用 @运算符来掩盖该错误:


A solution would be to use the @ operator, to mask that error :

if ($data = @getimagesize('not-existing.png')) {
    echo "OK";
} else {
    echo "NOT OK";
}

由于文件不存在,因此$ data仍为false;但不会显示警告.

As the file doesn't exist, $data will still be false ; but no warning will be displayed.


另一种解决方案是在使用getimagesize之前检查文件是否存在;这样的事情会做:


Another solution would be to check if the file exists, before using getimagesize ; something like this would do :

if (file_exists('not-existing.png') && 
    ($data = getimagesize('not-existing.png'))
   ) {
    echo "OK";
} else {
    echo "NOT OK";
}

如果文件不存在,则不会调用getimagesize,这意味着没有警告

If the file doesn't exist, getimagesize is not called -- which means no warning

仍然,此解决方案不是您应该用于另一台服务器上的图像的解决方案,并且可以通过HTTP访问(如果是这种情况),因为这意味着要向远程服务器发出两个请求.

Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.

对于本地图像,我想那还可以;我唯一看到的问题是当未掩盖读取错误时生成的通知.

For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.


最后:

  • 我允许在您的开发服务器上显示错误,
  • 并且不会在生产服务器上显示它们-请参阅 display_errors ,关于;-)

这篇关于当getimagesize找不到文件时处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆