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:
1 2 3 4 5 6 7 | 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; } |
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.
1 2 3 4 5 6 | 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; } |
Now to test it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $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','<br/>'; } |
The above will output:
1 2 3 4 5 6 7 8 9 10 | 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 |
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.
Possibly Related posts:

