Wednesday, 3 January 2018

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>";
}

0 comments:

Post a Comment