Validate IP Address in PHP

by Subramanian 2014-05-31 11:02:41

PHP - Validate IP Address:

A Valid IP address should be satisfied the below conditions.
  1. First part must be > 0.
  2. All parts of IP address will be <= 255
  3. No 0.0.0.0 match
  4. 00, 000 are not allowed in pairs if first digit starts with 0
  5. allowed for 0 first digit
The below php function "isValid()" is used to find given ip address is valid or not.
 
function isValidIp ( $ip )
{
    return !preg_match ( '/^([1-9]d|1d{0,2}|2[0-5]{2}).('.
                         '(0|1?d{0,2}|2[0-5]{2}).){2}(0|1?'.
                         'd{0,2}|2[0-5]{2})(:d{2,4})?$/',
                         (string) $ip ) 
                       ? false 
                       : true;
}

$ip="192.168.0.40";

if( isValidIp ( $ip ) )
{
   echo "Valid Ip";
}
else
{
    echo "Ip is Not Valid";
}
1034
like
0
dislike
0
mail
flag

You must LOGIN to add comments