≡ Menu

How to validate or detect an IPv4 or an IPv6 address in PHP?

It is sometimes necessary to validate an IP address which is entered by a user. It is also necessary to differentiate between an IPv4 and IPv6 addresses. Detecting an IPv4 address is not that difficult, but detecting an IPv6 address is quite complicated. Fortunately, PHP has a solution which can be used to validate and detect IPv4 and IPv6 addresses.

The PHP command is called filter_var.

The folowing code snippet validates an IPv4 address:

$valid = filter_var($ipaddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);

The filter_var command takes in as argument the ip address, a flag FILTER_VALIDATE which instructs it to validate and a flag that tells it to validate it as an IPv4 address – FILTER_FLAG_IPv4. The return code is TRUE if the $ipaddress is a valid IPv4 address and FALSE otherwise. So, this can be a very useful command to check and validate whether the entered string is indeed an IPv4 address.

The same thing can be done for an IPv6 address:

$valid = filter_var($ipaddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);

Note that the only thing that changed is the last argument flag which now says FILTER_FLAG_IPV6. This instructs the filter_var command to check and validate the entered IPv6 address.


Comments on this entry are closed.