PHP Functions to Validate Domain Names and IP Addresses

If you are similar to me in that you like to create PHP applications for the domain name industry or you have a need to validate domains or IPs, then this tutorial is for you.

Validate a Domain Name with PHP

The Valid Domain Function:

function validDom($domain) {
    if(!preg_match("/^([-a-z0-9]{2,100})\.([a-z\.]{2,8})$/i", $domain)) {
    return false;
    }
return $domain;
}//end validDom function.

Executing the ValidDom Function:

if(ValidDom($domain)) {
echo "<p style='color:green'>$domain is valid.</p>";
}else{
echo "<p style='color:red'>ERROR! $domain is NOT a valid domain name.</p>";
}

Validate an IP address with PHP

 

The Valid IP function:

function validIP($ip) {
$ipnums = explode(".", $ip);
    if(count($ipnums) != 4) {//if there is not 4 numbers to the IP return false
    return false;
    }
    
    foreach($ipnums as $ipnum) {//for ea. IP number make sure it's less than 256:
        if(!is_numeric($ipnum) || ($ipnum > 255)) {
        return false;
        }
    }
return $ip;//if made it this far, returns valid IP
}//end validIP function

Executing the ValidIP Function:

if(ValidIP($ip)) {
echo "<p style='color:green'>$ip is valid.</p>";
}else{
echo "<p style='color:red'>ERROR! $ip is NOT a valid IP address.</p>";
}

4 thoughts on “PHP Functions to Validate Domain Names and IP Addresses

    1. Perhaps you could explain what is not correct and offer a solution? There are hundreds of similar functions on the internet to verify domain names and this is just one that I found most helpful, but I am open to your suggestions, so please comment in detail. Thank you!

Leave a Reply

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