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 }
127.0.0.1.1 is considered a valid domain by this function.
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.
Works for me!
also its return full valid url when success…
I’m using: filter_var(‘admin@’.$domain, FILTER_VALIDATE_EMAIL); =)
That is smart , what works for emails works for domains
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!”
its working fine but need some tld validation cause testing something like this “exampledomain.432527889.com is a valid domain name!”