[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 :)

Eric Sizemore

About The Author

I’m a 24 year old Web Developer, Programmer, and Domainer. I specialize in PHP and MySQL, and have used both extensively since early 2005.

2 Comments

  1. sam says:

    Can this be used to validate rss feeds too?

    • Eric says:

      This can only be used to verify if a URL is valid, as far as returning a certain http code. In this case, it checks for 200 "OK", 301 "Permanent Redirect" or 302 "Moved Temporarily".

      If you're looking to validate RSS feeds, as far as if their structure is valid – you'd want to use something like http://www.feedvalidator.org

Leave A Reply