Check if a URL exists/is online.





10
Date Submitted Sun. May. 20th, 2007 5:27 AM
Revision 1 of 1
Scripter SecondV
Tags Online | PHP | URL
Comments 1 comments
This simple function will check if a url is valid (going by parse_url()) and if it's 'online' - by seeing if it returns a 302, 301, or 200 status code.
<?php

function is_valid_url($url)
{
    $url = @parse_url($url);

    if (!$url)
    {
        return false;
    }

    $url = array_map('trim', $url);
    $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
    $path = (isset($url['path'])) ? $url['path'] : '';

    if ($path == '')
    {
        $path = '/';
    }

    $path .= (isset($url['query'])) ? "?$url[query]" : '';

    if (isset($url['host']) AND $url['host'] != gethostbyname($url['host']))
    {
        if (PHP_VERSION >= 5)
        {
            $headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
        }
        else
        {
            $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

            if (!$fp)
            {
                return false;
            }
            fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
            $headers = fread($fp, 4096);
            fclose($fp);
        }
        $headers = (is_array($headers)) ? implode("\n", $headers) : $headers;
        return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
    }
    return false;
}

?>
<?php

if (is_valid_url('http://www.secondversion.com'))
{
        do_something();
}

?>

Eric S.

www.secondversion.com
-SV

Comments

Comments allow_url_fopen
Mon. May. 21st, 2007 1:14 PM    Helper Nico

Voting