PHP’s filter_var function can validate if an IP address is valid and can further validate if it is an IPv4 IP, IPv6 IP, or not within the private or reserved ranges. This post shows some examples using filter_var.
Minimum PHP version required
Note that the filter_var() function requires at least PHP version 5.2.0. It is included by default with versions >= 5.2.0
Validating an IP address
To simply check if an IP address is valid do the following:
if(filter_var($ip, FILTER_VALIDATE_IP)) { // it's valid } else { // it's not valid }
This will return the $ip address passed in if it’s valid or false if it is not. The basic usage above will be valid for any valid IP address including IPv4, IPv6, private and reserved range IPs.
Validate an IPv4 IP address
To validate an IPv4 IP address (e.g. 120.138.20.36) the FILTER_FLAG_IPV4 flag needs to be passed in as well. The following example will be valid for regular IPv4 IP address, as well as private and reserved ranges.
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { // it's valid } else { // it's not valid }
Validate an IPv4 address, excluding private range addresses
To validate an IPv4 address but not allow private range addresses to be included (e.g. 192.168.1.1) then use the FILTER_FLAG_NO_PRIV_RANGE flag as well. This is added to the flags passed with the | bitwise operator. For example:
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) { // it's valid } else { // it's not valid }
120.138.20.36 would be valid using the above example but 192.168.1.1 would not be.
Validate an IPv6 address
This is the same as for an IPv4 address but uses the FILTER_FLAG_IPV6 flag:
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { // it's valid } else { // it's not valid }
Combining FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6?
From my own testing I have discovered that combining FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6 (i.e. FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6) always seems to return false. You probably wouldn’t need to combine these two because that’s what the function does by default but I though’t it important to add a note about this.
Reserved Ranges
There are a large number of reserved ranges of IP addresses. To exclude these use the FILTER_FLAG_NO_RES_RANGE flag:
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) { // it's valid } else { // it's not valid }
Excluding Reserved and Private Ranges
The final example will validate any IPv4 and IPv6 IP address as long as it is not a reserved or private range IP address:
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { // it's valid } else { // it's not valid }
You could further limit the final example to just IPv4 or IPv6 addresses by adding “| FILTER_FLAG_IPV4” or “| FILTER_FLAG_IPV6”