开发者

How to detect page redirect with PHP?

开发者 https://www.devze.com 2022-12-30 20:46 出处:网络
I\'m trying to detect whether an image exists on a remote server. However, I\'ve tried several methods and can\'t get any of them to work.

I'm trying to detect whether an image exists on a remote server. However, I've tried several methods and can't get any of them to work.

Right now I'm trying to use this:

if (!CheckImageExists("http://img2.netcarshow.com/ABT-Audi_R8_2008_1024x768_wallpaper_01.jpg")) {
    print_r("DOES NOT EXIST");
} else {
    print_r("DOES EXIST");
};

function CheckImageExists($imgUrl) {
    if (fopen($imgUrl, "r")) {
        return true;
    } else {
        return false;
    };
};

But it returns 'true' whether the image actually exists or not (the above image should, but change it to gibberish and it still will return 'true'). I have a feeling it could be because if the URL does not exist, it redirects to the homepage of the site. But I don't know how to detect that开发者_JAVA技巧.

Thanks for any help!


Use cURL.

After fetching the resource, you can get the error code calling curl_errno().


The chances are you are getting a HTML page back into your $imgUrl that contains "404 image not found" or something similar.

You should be able to check the response for a code indicating that the request failed or redirected.


This should do the trick (using image size):

if (!CheckImageExists("http://www.google.com/intl/en_ALL/images/srpr/logo1w.png")) {
    echo 'DOES NOT EXIST';
} else {
    echo 'DOES EXIST';
};

function CheckImageExists($imgUrl) {
    if (@GetImageSize($imgUrl)) {
        return true;
    } else {
        return false;
    };
};


Got it working with Seb's method. Just used YQL to inspect the actual content of the page and determine if it's an error or not.

0

精彩评论

暂无评论...
验证码 换一张
取 消