Validating IP Addresses Using PHP
PHP 5.2+ offer an excellent function for validating IP Addresses: filter_var().
The filter_var() function offers several flags: FILTER_VALIDATE_IP, FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE and FILTER_FLAG_NO_RES_RANGE, used to filter or validate IP addresses based on whether the address is IPv4, IPv6 or within a reserved or private network range.
For the purpose of illustration, let’s assume we want to validate an IP address using a variable we call $ip_address. We will get this variable either as data input through a webform or by capturing the data using $ip_address=$_SERVER['REMOTE_ADDR']; when we serve up a webpage.
To validate the IP address ($ip_address) we might use the following function:
Test 1:
$ip_address = “192.168.1.0″;
if(filter_var($ip_address, FILTER_VALIDATE_IP)) {
$a = TRUE;
} else {
$a = FALSE;
}if($a) {
// script action to be taken
} else {
// Take alternative action
}
Test 1 will validate the IP address against all possible IPv4 and IPv6 addresses.
If we want to limit the IP Address to the IPv4 range we could add the FILTER_FLAG_IPV4 flag.
Test 2:
$ip_address = “192.168.1.0″;
if(filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$a = TRUE;
} else {
$a = FALSE;
}
if($a) {
// script action to be taken
} else {
// Take alternative action
}
Test 3:
$ip_address = “2001:0db8:85a3:0000:0000:8a2e:0370:7334″;
if(filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$a = TRUE;
} else {
$a = FALSE;
}
if($a) {
// script action to be taken} else {
// Take alternative action
}
Test 2 will validate as TRUE and Test 3 will validate as FALSE.
Perhaps we want to filter out IPv4 Bogons. We can do this by excluding private or reserved addresses:
Test 4:
$ip_address=”192.168.1.0″;
if(filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE )) {
$a = TRUE;} else {
$a = FALSE;
}
if($a) {
// script action to be taken} else {
// Take alternative action
}
Test 4 will validate as FALSE as 192.168.1.0 is within the 192.168.0.0/16 private range.
Test 5:
$ip_address=”224.0.0.1″;
if(filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE )) {
$a = TRUE;} else {
$a = FALSE;
}
if($a) {
// script action to be taken} else {
// Take alternative action
}
Test 5 will validate as FALSE as 224.0.0.1 is within the 224.0.0.0/3 Reserved Range.
The filter_var function is very powerful and can do much more than validate IP addresses.
Test these out in your own scripts and take action based on the results. Good luck and good computing.
Wow! You made a subject I’ve been struggling with, very easy. Thank you for the great information.