Skip to content

Instantly share code, notes, and snippets.

@mdjekic
Created February 7, 2018 11:41
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mdjekic/ac1f264e37bddfc63be8a042ced52e64 to your computer and use it in GitHub Desktop.
Save mdjekic/ac1f264e37bddfc63be8a042ced52e64 to your computer and use it in GitHub Desktop.
PHP function for validating CIDR notation format (ipv4, ipv6)
<?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 = 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;
}
@pavinjosdev
Copy link

Thanks for the gist, saved me some work today. Improved netmask validation in my fork. Hope you can merge the changes.

The fork invalidates netmasks like: /, /22chars, /17.8.9.

@jab4
Copy link

jab4 commented Feb 6, 2022

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment