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

//Not a valid domain name
About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].


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:

    @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 “ is a valid domain name!”

Leave a Reply

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