[PHP] – Check if a URL is valid/exists

Hello folks.

The following is a PHP function that will check a given URL to see if it’s valid, and check to see if it is responding (ie: returning Status: 200 OK).

First, the function

function is_valid_url($url)
{
    if (!($url = @parse_url($url)))
    {
        return false;
    }

    $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
    $url['path'] = (!empty($url['path'])) ? $url['path'] : '/';
    $url['path'] .= (isset($url['query'])) ? "?$url[query]" : '';

    if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host']))
    {
        if (PHP_VERSION >= 5)
        {
            $headers = @implode('', @get_headers("$url[scheme]://$url[host]:$url[port]$url[path]"));
        }
        else
        {
            if (!($fp = @fsockopen($url['host'], $url['port'], $errno, $errstr, 10)))
            {
                return false;
            }
            fputs($fp, "HEAD $url[path] HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
            $headers = fread($fp, 4096);
            fclose($fp);
        }
        return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
    }
    return false;
}

How to use it? It’s simple.

if (is_valid_url('http://google.com'))
{
    echo 'sweetness!';
}
else
{
    echo 'awww damn, :(';
}

Enjoy :)

Leave a Reply