$ip="255.255.47.12";
if(filter_var($ip,FILTER_VALIDATE_IP)){
echo " Correct , validation passed";
}else{
echo " Wrong , validation failed ";
}
FILTER_VALIDATE_IP can be used to validate IP address ( both IPv4 and IPv6 ) . This filter id = 275. Here is the code.
Filter Flags | DESCRIPTION |
---|---|
FILTER_FLAG_IPV4 | Only IPV4 formats are allowed |
FILTER_FLAG_IPV6 | Only IPV6 formats are allowed |
FILTER_FLAG_NO_PRIV_RANGE | Private range of IPV4 & IPV6 are not allowed. IPV4 :10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16 IPV6: Starting with FD or FC |
FILTER_FLAG_NO_RES_RANGE | Reserved range of IPV4 & IPV6 are not allowed. IPV4 :0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4 IPV6: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10 |
$ip='2002:0001:3238:DFE1:0063:0000:0000:FEFB'; //
if(filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_IPV6)){
echo " Correct , IP Validation passed ";
}else{
echo " Wrong , IP Validation failed ";
}
Output is
Correct , IP Validation passed
To check IPV4 address ONLY , we can add optional flag like this
$ip='2002:0001:3238:DFE1:0063:0000:0000:FEFB'; //
if(filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_IPV4)){
echo " Correct , IP Validation passed ";
}else{
echo " Wrong , IP Validation failed ";
}
Above validation will fail as we used FILTER_FLAG_IPV4
to check one IPV6 address. $ip='127.0.0.0'; //Change this value to check different IP
if(filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_IPV4)){
echo " Correct , IP Validation passed ";
}else{
echo " Wrong , IP Validation failed ";
}
Output is here
Correct , IP Validation passed
No private range of IP is allowed by using Flag FILTER_FLAG_NO_PRIV_RANGE
$ip='10.0.0.0'; //Change this value to check different IP
if(filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_NO_PRIV_RANGE)){
echo " Correct , IP Validation passed ";
}else{
echo " Wrong , IP Validation failed ";
}
Output is
Wrong , IP Validation failed
No reserve range of IP address are allowed by using FILTER_FLAG_NO_RES_RANGE
$ip='169.254.0.0'; //Change this value to check different IP
if(filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_NO_RES_RANGE)){
echo " Correct , IP Validation passed ";
}else{
echo " Wrong , IP Validation failed ";
}
Output is
Wrong , IP Validation failed