Thursday, April 29, 2010

2:57 AM

If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to validate the IP address using regular expression in PHP.

As you guyz know, IP address consists four parts. Each parts separated by period “.” and these part consists the digits which ranges from 0 to 255.
Function to validate IP address in PHP using Regular Expression

//function to validate ip address format in php by Roshan Bhattarai(http://roshanbh.com.np)
function validateIpAddress($ip_addr)
{
  //first of all the format of the ip address is matched
  if(preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$ip_addr))
  {
    //now all the intger values are separated
    $parts=explode(".",$ip_addr);
    //now we need to check each part can range from 0-255
    foreach($parts as $ip_parts)
    {
      if(intval($ip_parts)>255 || intval($ip_parts)<0)
      return false; //if number is not within range of 0-255
    }
    return true;
  }
  else
    return false; //if format of ip address doesn't matches
}

As you can see above, first of all the format of the “$ip_addr” is validated using regular expression. In the regular expression “\d{1,3}” means that there should be digits which can be either 1 to 3 digits because a IP Adress can be “222.0.123.12″ or 
“12.15.123.5″. So, each part can consists 1 to 3 digits.

After validating the format using regular expression, each part of the IP address is separated using period(“.”) using explode() function available in PHP. And finally, it is checked that each part of the IP address is between 0 to 225 or not.

0 comments: