views:

87

answers:

4

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.

Thanks for any help!

A: 

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.

SLC
How would I go about checking the code? Because as I said above, one method I tried would return code '200' whether the image actually existed, or didn't exist and just redirected.
blabus
+1  A: 

Use cURL.

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

Seb
I've tried that method as well, however, I get back a code '200' whether the image actually exists or if it doesn't and just redirects. So I don't know how I can use that to distinguish between the two.
blabus
Code 200 is for OK, which means it's not a 404 so forget about that. I see that if I request http://img2.netcarshow.com/ABT-Audi_R8_2008_1024x768_wallpaper_01.jpg2, which doesn't exist, I get a valid page. Given this site is not W3C compliant (does not send 404), you'll need to handle this one manually - i.e. inspect the received content to see if it's an 'custom' 404 page.
Seb
A: 

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;
    };
};
Codex73
I've tried that method as well, but it always returns 'false', even for images that do exist.
blabus
A: 

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.

blabus