PHP: Validate an IP Address
March 13th, 2010
2 comments
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.
Categories: Programming Data Filtering, IP, IP address, IPv4, IPv6, PHP, Programming, Regex, Regular expression, Validation


23
103
28
7