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;


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.