普通网友 2009-09-01 18:19
浏览 261
已采纳

当getimagesize找不到文件时处理错误

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.

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

try: getimagesize($img) $works = true
catch: $works = flase
  • 写回答

3条回答 默认 最新

  • douyi1899 2009-09-01 18:41
    关注

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

    This code :

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

    will get you a

    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";
    }
    

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


    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";
    }
    

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

    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.


    Finally :

    • I would allow errors to be displayed on your developpement server,
    • And would not display those on your production server -- see display_errors, about that ;-)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度