Validating IP-Addresses in PHP

Using PHP functions can be surprising at times. Validating IP-Addresses using Validate Filters seems to be one of those. There are several flags you can set to specify what kind of IP-Addresses you wan’t to consider as valid, namely:

  • FILTER_FLAG_IPV4 : Validates only IPv4 Addresses
  • FILTER_FLAG_IPV6 : Validates only IPv6 Addresses
  • FILTER_FLAG_NO_PRIV_RANGE : Consider IPs from the private range as invalid
  • FILTER_FLAG_NO_RES_RANGE : Consider IPs from the reserved range as invalid

In the PHP docs, the explanation for those flags says as follows:

Validates value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges.

Uhm, yeah. Okay so just to make it clear how that works, here are a few examples (first the surprising one):

$ip = "2001:db8:0:8d3:0:8a2e:70:7344";
$flags = FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6;
filter_var( $ip, FILTER_VALIDATE_IP, $flags );
=> false

$ip = "30.17.132.147";
$flags = FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6;
filter_var( $ip, FILTER_VALIDATE_IP, $flags );
=> false

If FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6 are specified together, FILTER_VALIDATE_IP seems to always return false, which was rather unexpected for me. The rest is quite understandable, though:

$ip = "2001:db8:0:8d3:0:8a2e:70:7344";
filter_var( $ip, FILTER_VALIDATE_IP );
=> "2001:db8:0:8d3:0:8a2e:70:7344"

$ip = "30.17.132.147";
filter_var( $ip, FILTER_VALIDATE_IP );
=> "30.17.132.147"

These both validate, as FILTER_VALIDATE_IP defaults to allowing both IPv4 and IPv6.

For an explanation on what the private range and reserved range flags do, check out the Wikipedia page on Reserved IP addresses.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>