Google News
logo
PHP Program to Validate an IP address
In the following example of PHP program that uses the `filter_var()` function to validate an IP address :
Program :
<?php
// Example IP addresses to validate
$ip1 = "192.168.0.1";
$ip2 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
$ip3 = "not_an_ip_address";

// Validate IP addresses
if (filter_var($ip1, FILTER_VALIDATE_IP)) {
    echo "$ip1 is a valid IP address\n";
} else {
    echo "$ip1 is not a valid IP address\n";
}

if (filter_var($ip2, FILTER_VALIDATE_IP)) {
    echo "$ip2 is a valid IP address\n";
} else {
    echo "$ip2 is not a valid IP address\n";
}

if (filter_var($ip3, FILTER_VALIDATE_IP)) {
    echo "$ip3 is a valid IP address\n";
} else {
    echo "$ip3 is not a valid IP address\n";
}
?>
This program defines three example IP addresses to validate. The `filter_var()` function is used to validate each IP address using the `FILTER_VALIDATE_IP` filter. The program then outputs whether each IP address is valid or not.

In this example, the first IP address is a valid IPv4 address, the second IP address is a valid IPv6 address, and the third IP address is not valid, so the output of the program will be :
Output :
192.168.0.1 is a valid IP address
2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid IP address
not_an_ip_address is not a valid IP address