Validating an IP address in PHP

A question asked privately:

How can I validate a user-submitted IP address ?

One approach is to offload the validation burden to the ip2long() function:

function isValidIPAddress ($ip) {
  $long = ip2long($ip);
  if (($long == FALSE) or ($long == -1)) {
    return false;
  } else {
    return true;
  }
}

The problem with this approach is that ip2long() will consider an incomplete IP address (such as 192.168.0) to be valid. If this is not acceptable, there’s an alternative:

function isValidIPAddress ($ip) {
  $segments = explode('.', $ip);
  if (count($segments) <> 4) {
    return false;
  }
  foreach ($segments as $segment) {
    if (!is_numeric($segment)
         or ($segment < 0)
         or ($segment > 255)) {
      return false;
    }
  }
  return true;
}

* * * * *

This entry was posted in Answers, Technology. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *