Showing posts with label PHP Validate Domain name. Show all posts
Showing posts with label PHP Validate Domain name. Show all posts

Monday, 24 September 2018

Validate domain name using filter_var function in PHP

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
1
2
3
4
if(!filter_var_domain('www.gmail.com.'))
{
//Not a valid domain name
}