PHP FILTER_VALIDATE_IPFilter


PHP Filter 参考手册Complete PHP Filter Reference Manual

Definition and Usage

The FILTER_VALIDATE_IP filter validates the value as an IP address.

  • Name: "validate_ip"
  • ID-number: 275

Possible flags:

  • FILTER_FLAG_IPV4 - Requires the value to be a valid IPv4 IP (e.g., 255.255.255.255).
  • FILTER_FLAG_IPV6 - Requires the value to be a valid IPv6 IP (e.g., 2001:0db8:85a3:08d3:1319:8a2e:0370:7334).
  • FILTER_FLAG_NO_PRIV_RANGE - Requires the value not to be in the RFC-specified private range IP (e.g., 192.168.0.1).
  • FILTER_FLAG_NO_RES_RANGE - Requires the value not to be in the reserved IP range. This flag accepts IPv4 and IPv6 values.

Example 1

<?php
$ip = "192.168.0.1";

if(!filter_var($ip, FILTER_VALIDATE_IP))
{
echo "IP is not valid";
}
else
{
echo "IP is valid";
}
?>

The output of the code is as follows:

IP is valid


Example 2

<?php
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";

if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))
{
echo "IP is not valid";
}
else
{
echo "IP is valid";
}
?>

The output of the code is as follows:

IP is valid


PHP Filter 参考手册Complete PHP Filter Reference Manual Other Extensions