PHP – How to Filter/validate IP Address?
Introduction –
Many times, we need to validate an IP Address. Of course, and IP address may be of different formats for ipv4 and ipv6. An IP address may also need to be within a range of private or reserved ranges. The filter extension makes it possible to discern these differences and to validate an IP address to fit most needs. In its simplest form the validation of a URL will look like this….
// Valid IP address
$ip = “192.168.0.1”;
if(filter_var($ip, FILTER_VALIDATE_IP) === FALSE)
{
echo “$ip is not a valid IP”;
}
else
{
echo “$ip is valid”;
}
?>
As we have supplied the above with a valid IP address it validates and all is well. But now we may wish to validate an IPv6 address or an address with a private range. The IP Filter has several flag with which to validate an IP address with.
Flag are for IP Filter –
-
FILTER_FLAG_IPV4
-
FILTER_FLAG_IPV6
-
FILTER_FLAG_NO_PRIV_RANGE
-
FILTER_FLAG_NO_RES_RANGE
** Starting at the top we will check to see if an IP is a valid IPv4 address.
// Valid IP address
$ip = “192.168.0”;
// try to validate as IPV4 address
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE)
{
echo “$ip is not a valid IP”;
}
else
{
echo “$ip is valid”;
}
?>
In the above example the IP address has failed to validate as it is not a complete IPv4 address. It would need to be of the form of the example that preceded it, 192.168.0.1 to validate. This is fine, but growth of the net has seen us run out of IPv4 addresses and so we need to validate against IPv6 addresses also….
Thank you,
Santhosh Tirunahari