Validating an IP Address with PHP
by Mark Sanborn on June 2, 2008
For security purposes, all user input should be validated before accepting. In this case we are going to run a regular expression to determine whether or not an IP address is valid. This function could be used on forms or web applications where you ask the user for an IP address.
Last week I wrote about Validating Telephone Numbers With PHP and Using PHP to Accept Only Numbers From User Input.
So here it is.
The Function
function valIP($string) {
if (preg_match(
'^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$^',
$string)) {
echo $string;
} else {
echo 'Invalid IP Address';
}
}
2 comments
I wish I knew ANYTHING about regex’s
They are SOOOO powerful.
by Jade Robbins on June 3, 2008 at 11:59 am #
[...] can also validate telephone numbers, ip addresses, and zipcodes. Remember everything that a user can submit should be validated/sanitized. This goes [...]
by Validating Usernames with PHP on June 10, 2008 at 9:21 pm #