[PHP] – Valid URL Checking

To keep it short and sweet today, the following is a PHP function that will check the input for a valid URL, and will also 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

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

3 thoughts to “[PHP] – Valid URL Checking”

    1. 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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.