Validating an IP Address with PHP

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 Responses to "Validating an IP Address with PHP"
  1. Jade Robbins on June 3rd, 2008

    I wish I knew ANYTHING about regex’s :( They are SOOOO powerful.

  2. Validating Usernames with PHP on June 10th, 2008

    [...] can also validate telephone numbers, ip addresses, and zipcodes. Remember everything that a user can submit should be validated/sanitized. This goes [...]

Leave a reply