PHP: is_ip() to test if a string is a valid IP address

I needed to test if a string was a valid IP address or not. PHP has filter_var() which tests for a lot of common things (email addresses, urls, etc) but I can never remember the syntax. Here is a simple wrapper function to match IPv4 and IPv6 addresses.

function is_ip($str) {
    $ret = filter_var($str, FILTER_VALIDATE_IP);

    return $ret;
}

If you just want to match a specific type of addresses:

function is_ipv4($str) {
    $ret = filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);

    return $ret;
}

function is_ipv6($str) {
    $ret = filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);

    return $ret;
}
Leave A Reply
All content licensed under the Creative Commons License