Validate domain name using filter_var function in php

By | March 21, 2013

The filter_var function of php is capable of validating many things like emails, urls, ip addresses etc. It does not have a direct option to validate a domain name however. So I coded up this little snippet that the filter_var function with a little tweak so that it can validate domain names as well.

function filter_var_domain($domain)
{
	if(stripos($domain, 'http://') === 0)
	{
		$domain = substr($domain, 7); 
	}
	
	///Not even a single . this will eliminate things like abcd, since http://abcd is reported valid
	if(!substr_count($domain, '.'))
	{
		return false;
	}
	
	if(stripos($domain, 'www.') === 0)
	{
		$domain = substr($domain, 4); 
	}
	
	$again = 'http://' . $domain;
	return filter_var ($again, FILTER_VALIDATE_URL);
}

Now use it as

if(!filter_var_domain('www.gmail.com.'))
{
//Not a valid domain name
}





Last Updated On : 21st March 2013

Related Post

7 thoughts on “Validate domain name using filter_var function in php

  1. The Kay

    This code example is bad and should not be used! It is a genuent security risk!

    Shit like this returns a valid result:
    filter_var_domain(‘www.137.com?”(OR(1=1))’)

    @Felipe Braz’s solution is not as insecure as the Posters.

    Blog posts and “solutions” are the reason PHP get a bad rep. So please remove this post so less experienced coders don’t use this in their application.

  2. apalah

    thanks for the snippet you save my time..

    do you have more code snippet for check valid tld cause its still say something like this “domainexample.helloworld is a valid domain name!”

  3. apalah

    its working fine but need some tld validation cause testing something like this “exampledomain.432527889.com is a valid domain name!”

Leave a Reply to The Kay Cancel reply

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