PHP: Validate an IP Address

So you need to check if some string is a valid IP address. You could simply test it against a regular expression:

[cc lang=’php’ ]
function is_valid_ipv4($ip)
{
return preg_match(‘/\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.’.
‘(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.’.
‘(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.’.
‘(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/’, $ip) !== 0;
}
[/cc]
Regular Expression obtained here

This will actually work for most situations, but it’s lacking in a few ways. Suppose you want to exclude private or reserved IP addresses. Maybe you want to validate IPv6 addresses too; not just IPv4.

Enter PHP’s Data Filtering Extension. It just works, and you don’t have to worry about maintaining (or properly applying) complex regular expressions.

[cc lang=’php’ ]
function is_valid_ip($ip, $include_priv_res = true)
{
return $include_priv_res ?
filter_var($ip, FILTER_VALIDATE_IP) !== false :
filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
}
[/cc]

Now to test it.

[cc lang=’php’ ]
$ips = array(‘72.215.140.69’,
‘192.168.0.1’,
‘127.0.0.1’,
‘10.0.0.1’,
‘255.255.255.0’,
‘andrewensley.com’,
‘255.255.256.0’,
‘::1’,
‘fe00::0’,
‘2001:4860:0:1001::68′);

foreach($ips as $ip)
{
echo $ip,’ ‘, is_valid_ip($ip, false) ? ‘yes’ : ‘no’,’
‘;
}
[/cc]

The above will output:

[cc]
72.215.140.69 yes
192.168.0.1 no
127.0.0.1 yes
10.0.0.1 no
255.255.255.0 no
andrewensley.com no
255.255.256.0 no
::1 yes
fe00::0 yes
2001:4860:0:1001::68 yes
[/cc]

Thank you PHP for making this otherwise complex task very simple. And even better: it’s fast!

I tested the regular expression and the filter_var functions by running each 100,000 times. Here are the timings for each test:

  • 1.53423094749 seconds with the filter_var function
  • 3.1516289711 seconds with the regular expression function

Not bad! Happy filtering.

Andrew

Programmer / Musician / Soccer Player

5 thoughts to “PHP: Validate an IP Address”

    1. The first example was a single-purpose regular expression for all IPv4 addresses.  The second solution I provided uses filter_var() with options for including or excluding private and reserved addresses.  It will also work with IPv6 addresses.

  1. Just thought I would inform you that 192.168.0.1 is a valid IP address and it’s come out as not.

Leave a Reply

Your email address will not be published. Required fields are marked *