PHP: check valid ipaddress or CIDR notation range


This function checks for a valid IP address or CIDR notation address range.

<?php

/**
 * @author phptuts
 * @copyright 2012
 * @link http://tutorialspots.com/
 */

function valid_ip_cidr($cidr, $must_cidr = false)
{
    if (!preg_match("/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(\/[0-9]{1,2})?$/", $cidr))
    {
        $return = false;
    } else
    {
        $return = true;
    }
    if ($return == true)
    {
        $parts = explode("/", $cidr);
        $ip = $parts[0];
        $netmask = $parts[1];
        $octets = explode(".", $ip);
        foreach ($octets as $octet)
        {
            if ($octet > 255)
            {
                $return = false;
            }
        }
        if ((($netmask != "") && ($netmask > 32) && !$must_cidr) || (($netmask == ""||$netmask > 32) && $must_cidr))
        {
            $return = false;
        }
    }
    return $return;
}
?>

Example of usage:

<?
var_dump(valid_ip_cidr('145.3.233.45')); //true
var_dump(valid_ip_cidr('345.3.233.45')); //false
var_dump(valid_ip_cidr('145.3.233.45/11')); //true
var_dump(valid_ip_cidr('345.3.233.45/11')); //false
var_dump(valid_ip_cidr('145.3.233.45',true)); //false
var_dump(valid_ip_cidr('145.3.233.45/41',true)); //false
?>

Leave a Reply