PHP Detecting if source image url link leads to a “broken” image?

前端 未结 8 1583
迷失自我
迷失自我 2020-12-30 03:56

Suppose you have a thumbnail generator script that accepts source images in the form of a URL. Is there a way to detect if the source URL is \"broken\" - whether nonexistent

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 04:37

    Fast Solution for broken or not found images link
    i suggest you that don't use getimagesize() because it will 1st download image then it will check images size+if this will not image then it will throw exception so use below code

    if(checkRemoteFile($imgurl))
    {
    //found url, its mean
    echo "this is image";
    }
    
    function checkRemoteFile($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        // don't download content
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(curl_exec($ch)!==FALSE)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    

    Note: this current code help you to identify broken or not found url image this will not help you to identify image type or headers

提交回复
热议问题