Validate CIDR notation in PHP

0
2773
Validate CIDR notation in PHP
Validate CIDR notation in PHP

Previously, I’ve shown you how to validate IP address. In this post, I will show you how to validate CIDR notation in PHP.

If you do not know, CIDR (Classless Inter-Domain Routing) is the notation format to determine how to allocate IP address and IP routing over the network, for example (taken from Wikipedia):

  • 198.51.100.0/22 represents the 1024 IPv4 addresses from 198.51.100.0 to 198.51.103.255.
  • 2001:db8::/48 represents the block of IPv6 addresses from 2001:db8:0:0:0:0:0:0 to 2001:db8:0:ffff:ffff:ffff:ffff:ffff.

As you can see, to validate a CIDR string, we need to:

  • split the notation string into two parts separated by / character.
  • the left part must be a valid IP address, IPv4 or IPv6.
  • the second part must be a valid netmask value.

In short, this is how we validate CIDR notation in PHP:

function isValidCIDR($cidr)
{
    $parts = explode('/', $cidr);
    // it should have only two parts
    if(count($parts) != 2) {
        return false;
    }

    $ip = $parts[0];
    $netmask = intval($parts[1]);

    if($netmask < 0) {
        return false;
    }
    // check if it is a valid IPv4
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        // netmask for IPv4 should be less than 32
        return $netmask <= 32;
    }

    // check if it is a valid IPv6
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        // netmask should be less than 128
        return $netmask <= 128;
    }

    // well, if no match, then it is an invalid CIDR string
    return false;
}

Let’s test with a CIDR string:

$cidr = "2001:4860:4860::8888/32";

if (isValidCIDR($cidr)) {
    echo $cidr . " is a valid CIDR notation string";
} else {
    echo $cidr . " is NOT a valid CIDR notation string";
}

It should output as:

2001:4860:4860::8888/32 is a valid CIDR notation string

Have fun!