Using PHP, how do I validate that a string is a valid IP?
Examples of valid strings:
Try it with filter_var
Example:
if(filter_var('127.0.0.1', FILTER_VALIDATE_IP) !== false) {
// is an ip
} else {
// is not an ip
}
If you now have a string like foo
, 127.0.0.bla
or similar, filter_var
will return false
. Valid IPs like 10.1.10.10
, ::1
are considered as valid.
Notice
Also you have to check on !== false
, because filter_var
returns the value, if it is valid and false
if it isn't (e.g. filter_var("::1", FILTER_VALIDATE_IP)
will return ::1
, not true
).
Flags
You could also use some of the following flags:
FILTER_FLAG_IPV4 (Filter for IPV4)
FILTER_FLAG_IPV6 (Filter for IPV6)
FILTER_FLAG_NO_PRIV_RANGE (Disallow IPs from the private range)
FILTER_FLAG_NO_RES_RANGE (Disallow IPs from the reserved range)
filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)
If $ip
is 127.0.0.1
the function will return false
.
Notice Awkwardly ::1
is ok for FILTER_FLAG_NO_PRIV_RANGE
, but 127.0.0.1
isn't.