-
-
Save pavinjosdev/cb1d636ea9dc2bd201d54107d10650c5 to your computer and use it in GitHub Desktop.
PHP function for validating CIDR notation format (ipv4, ipv6)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Validates the format of a CIDR notation string | |
* | |
* @param string $cidr | |
* @return bool | |
*/ | |
function validateCidr($cidr) | |
{ | |
$parts = explode('/', $cidr); | |
if(count($parts) != 2) { | |
return false; | |
} | |
$ip = $parts[0]; | |
$netmask = $parts[1]; | |
if (!preg_match("/^\d+$/", $netmask)){ | |
return false; | |
} | |
$netmask = intval($parts[1]); | |
if($netmask < 0) { | |
return false; | |
} | |
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { | |
return $netmask <= 32; | |
} | |
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { | |
return $netmask <= 128; | |
} | |
return false; | |
} | |
?> |
@joho1968 The integer conversion does appear to be redundant, I believe the check for less than zero was to prevent negative integers from being passed through. Regex can't be good for speed, perhaps you could use some built-ins to check if the netmask is a positive integer?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, I think the preg_match regex could be changed to '/^\d{1,3}$/' for further validation.