Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    PHP Check the domain name is valid

    Sometimes we need to validate the domain name, and we can easily do it by using a regular expression or by using some of the inbuilt functions in PHP. But it does not mean that the domain name is actually registered and working.

    To solve this problem, I have created a function to validate the domain name.

    It's a complete validation of the domain name.

    Features

    • Adding HTTP if already not in the domain.
    • Validates only HTTP and https in a scheme.
    • Validates URL.
    • Checks A record of the domain name.
    • Validates server header response.
    • Validates the host.
    • Removes www. if you don't want it.

    Function:

    function is_valid_domain($url){
    
        $validation = FALSE;
        /*Parse URL*/
        $urlparts = parse_url(filter_var($url, FILTER_SANITIZE_URL));
        /*Check host exist else path assign to host*/
        if(!isset($urlparts['host'])){
            $urlparts['host'] = $urlparts['path'];
        }
    
        if($urlparts['host']!=''){
           /*Add scheme if not found*/
            if (!isset($urlparts['scheme'])){
                $urlparts['scheme'] = 'http';
            }
            /*Validation*/
            if(checkdnsrr($urlparts['host'], 'A') && in_array($urlparts['scheme'],array('http','https')) && ip2long($urlparts['host']) === FALSE){ 
                $urlparts['host'] = preg_replace('/^www\./', '', $urlparts['host']);
                $url = $urlparts['scheme'].'://'.$urlparts['host']. "/";            
                
                if (filter_var($url, FILTER_VALIDATE_URL) !== false && @get_headers($url)) {
                    $validation = TRUE;
                }
            }
        }
    
    if(!$validation){
        echo "Its Invalid Domain Name.";
    }else{
        echo " $url is a Valid Domain Name.";
    }
    
    }
    
    //Function Call
    is_valid_domain('//www.w3schools.in');
    


    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.