Return to Snippet

Revision: 7954
at August 24, 2008 11:24 by goo


Initial 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
Host: $url[host]

");
            $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();
}

?>

Initial URL
http://www.bytemycode.com/snippets/snippet/657/

Initial Description


Initial Title
PHP Saber si una URL es correcta

Initial Tags
url, php

Initial Language
PHP