PHP – How to Filter/validate IP Address?

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

Similar Posts:

Be Sociable, Share!

2 Replies to “PHP – How to Filter/validate IP Address?”

  1. Great web-site!!! You did an amazing job!!! I enjoyed watching the videos!!! You guys are great!
    Talking about ideas, there\s this really good show, which I like a lot, and I\m sure you\ve heared about it. It\s called STOMP. What these guys do is so cool, I saw them live in NY. I\m sure you can do the same and even better. It really turns people on. Just an idea, hope it could be any helpful.
    ehowa
    nicole kidman in
    alta definizione
    bianchi

Leave a Reply

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