PHP: Test if an Image URL is Online CodeUnit 25 MAY 2011

Here is a quick and dirty simple function to check whether or not an image URL is valid, in other words the image is online, by running a quick get_headers check combined with some REGEX wizardry.

The function returns a simple true if the image/URL is active and false if it is not (i.e. the server returns a 404).

function url_exists($url) {
    $hdrs = @get_headers($url);
    return is_array($hdrs) ? preg_match('/^HTTP\/\d+\.\d+\s+2\d\d\s+.*$/',$hdrs[0]) : false;
}

Nifty.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.