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(
function validateIpAddress($ip_addr)
  //first of all the format of the ip address is matched
    //now all the intger values are separated
    //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;
    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 “″ or 
“″. 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.