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
?>

Recent search terms:

  • https://yandex ru/clck/jsredir?from=yandex ru;search;web;;&text=&etext=1831 q_RkxiKb-6BMoW9EPSch9l_6eUTcPTtxAyRpwiOn66k-f6_AZugsUnkqyVYQDY_4 c0cfadabe9dcb932f510036223f86e0c508a4f40&uuid=&state=_BLhILn4SxNIvvL0W45KSic66uCIg23qh8iRG98qeIXme
  • https://yandex ru/clck/jsredir?from=yandex ru;search;web;;&text=&etext=1835 xr9jmQ604gaO5J4DQE1bk4puNfHdVu9dYL4ATetxbCQgpft09ihbd2WYJzW0LnaU d7a46c95f03347c662752c41a618947697d84183&uuid=&state=_BLhILn4SxNIvvL0W45KSic66uCIg23qh8iRG98qeIXme

Leave a Reply