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):
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:
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.