纠正PHP方式来检查外部图像是否存在? [英] Correct PHP way to check if external image exists?

查看:158
本文介绍了纠正PHP方式来检查外部图像是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道答案中至少有10个相同的问题,但它们似乎都没有完美地为我工作。我正在尝试检查内部或外部图像是否存在(图像URL是否有效?)。

I know that there are at least 10 the same questions with answers but none of them seems to work for me flawlessly. I'm trying to check if internal or external image exists (is image URL valid?).


  1. fopen($ url,'r')失败,除非我使用 @fopen()

Warning: fopen(http://example.com/img.jpg) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in file.php on line 21


  • getimagesize($ img)在图像不存在时失败(PHP 5.3.8):

  • getimagesize($img) fails when image doesn't exist (PHP 5.3.8):

    Warning: getimagesize() [function.getimagesize]: php_network_getaddresses: getaddrinfo failed
    


  • CURL失败,因为它不是一些服务器支持(虽然它主要出现在各处)。

  • fileExists()失败,因为它不能与外部一起工作网址和
    无法检查我们是否正在处理图片。

  • CURL fails because it isn't supported by some servers (although it's present mostly everywhere).
  • fileExists() fails because it doesn't work with external URLs and can't possibly check if we're dealing with image.
  • 四种方法是最常见的答案对这样的问题是错误的。这样做的正确方法是什么?

    Four methods that are the most common answers to such question are wrong. What would be the correct way to do that?

    推荐答案

    getimagesize($ img)在图像处理时失败不存在:我不确定你明白你想要什么......

    getimagesize($img) fails when image doesn't exist: am not sure you understand what you want .....

    来自PHP DOC


    getimagesize()函数将确定任何给定图像文件的大小,并返回尺寸以及文件类型和要在正常情况下使用的高度/宽度文本字符串HTML IMG标记和相应的HTTP内容类型。

    The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondant HTTP content type.

    失败时,返回FALSE。

    示例

    $img = array("http://i.stack.imgur.com/52Ha1.png","http://example.com/img.jpg");
    foreach ( $img as $v ) {
        echo $v, getimagesize($v) ? " = OK  \n" : " = Not valid \n";
    }
    

    输出

    http://i.stack.imgur.com/52Ha1.png = OK  
    http://example.com/img.jpg = Not valid 
    

    getimagesize 工作正常

    • PHP 5.3.19
    • PHP 5.4.9

    编辑


    @Paul。但你的问题基本上是在说我该怎么办?处理这个,所以当出现错误情况时我不会收到错误。答案就是你做不到。因为所有这些功能都会在出现错误时触发错误。所以(如果你不想要错误)你会压制它。这在生产中都不重要,因为你不应该显示错误;-) - DaveRandom

    这篇关于纠正PHP方式来检查外部图像是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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