You are currently viewing PHP: How to Validate Domain Names

PHP: How to Validate Domain Names

Validating domain names is a common requirement in web development projects, ensuring that user input adheres to the correct format and structure. In PHP, you can leverage various techniques and functions to validate domain names effectively. In this blog post, we will explore how to validate domain names in PHP. We will cover essential concepts, including regular expressions, and the filter_var() function.

The PHP code defines a function called validate_domain() that validates a domain name using either a regular expression or, if defined, the FILTER_VALIDATE_DOMAIN filter (defined in PHP 7.0.0 or later).

<?php

$domain = 'coderscratchpad.com';

/*
    Note that I included all these filters for educational purposes,
    to demonstrate the different ways this could be done.
*/
function validate_domain($domain) {

    if(defined('FILTER_VALIDATE_DOMAIN')) {

        return filter_var($domain, FILTER_VALIDATE_DOMAIN);

    }

    $regexp = "/^[a-z0-9]+([\-.][a-z0-9]+)*\.[a-z]{2,5}$/i";

    if(defined('FILTER_VALIDATE_REGEXP')) {

        $options = [
            "options" => [
                "regexp" => $regexp
            ]
        ];

        return filter_var($domain, FILTER_VALIDATE_REGEXP, $options);

    }

    return preg_match($regexp, $domain);

}

if (validate_domain($domain)) {

    echo "The domain '$domain' is valid.";

} else {

    echo "The domain '$domain' is not valid.";

}

The code should work correctly for validating domain names in PHP even if the FILTER_VALIDATE_DOMAIN filter is not defined. I hope that’s been informative to you. If you wish to learn more about PHP, please subscribe to our newsletter today and continue your PHP learning journey with us!

Leave a Reply