Validate IP address in PHP

0
1851
Validate IP address in PHP
Validate IP address in PHP

Just another day for a PHP coding tip. In this post, I will show you how to validate IP address in PHP.

To validate IP address in PHP, we will use the function filter_var for the purpose.

To filter IPv4, we will use the FILTER_FLAG_IPV4.

function isValidIpv4($ip) {
  return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
}

$ip = "124.112.12.111";

if (isValidIpv4($ip)) {
  echo $ip . " is a valid IPv4 address";
} else {
  echo $ip . " is NOT a valid IPv4 address";
}

To filter IPv6, we will use the FILTER_FLAG_IPV6.

function isValidIpv6($ip) {
  return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
}

$ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";

if (isValidIpv6($ip)) {
  echo $ip . " is a valid IPv6 address";
} else {
  echo $ip . " is NOT a valid IPv6 address";
}

To validate both IPv4 and IPv6, we will omit the last flag parameter.

function isValidIp($ip) {
  return filter_var($ip, FILTER_VALIDATE_IP);
}

$ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";

if (isValidIp($ip)) {
  echo $ip . " is a valid IP address";
} else {
  echo $ip . " is NOT a valid IP address";
}

That’s it, very simple to validate IP address in PHP.

Have fun!