Validating an IP Address with PHP

Last updated: Jun 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';
    }
}

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Get notified on new posts or other things I'm working on

Share: