It’s common to use a regular expression to validate IP addresses.
However I’ve run into couple reliable ways to validate IP address without help of regexps. This should make code cleaner and easier to read or debug in case of any issues.
The first way is to use PHP function filter_var() which returns the filtered data, or false if the filter fails.
$ip = filter_var($ip, FILTER_VALIDATE_IP);
if ($ip !== false)
{
// IP address is valid
} |
$ip = filter_var($ip, FILTER_VALIDATE_IP);
if ($ip !== false)
{
// IP address is valid
}
Note that filter_var() has been supported since PHP 5.2. So it will not work for ‘older’ production environments.
So here comes another way to validate an IP address which should work even for PHP 4.
if (long2ip(ip2long($ip))) == $ip)
{
// IP address is valid
} |
if (long2ip(ip2long($ip))) == $ip)
{
// IP address is valid
}
Also fliter_var() unlike ip2long()/long2ip() supports IPv6. For instance, there are four additional flags:
- FILTER_FLAG_IPV4 – allow only IPv4;
- FILTER_FLAG_IPV6 – allow only IPv6;
- FILTER_FLAG_NO_PRIV_RANGE – dot not allow IP from private range;
- FILTER_FLAG_NO_RES_RANGE – do not allow IP from reserved range.
For example, the code to allow only IPv6 not from reserved range should look like this:
$ip = "2a01:e35:aaa4:6860:a5e7:5ba9:965e:cc93";
$ip = filter_var($ip, FILTER_VALIDATE_IP, array(
FILTER_FLAG_IPV6, FILTER_FLAG_NO_RES_RANGE));
if ($ip !== false)
{
// IP address is valid
} |
$ip = "2a01:e35:aaa4:6860:a5e7:5ba9:965e:cc93";
$ip = filter_var($ip, FILTER_VALIDATE_IP, array(
FILTER_FLAG_IPV6, FILTER_FLAG_NO_RES_RANGE));
if ($ip !== false)
{
// IP address is valid
}