Validate IP Address in PHP

Description: Checks to make sure a given IP address fits the standard format.
Tested Platform: PHP 7+
Language: PHP
// Takes in an IP (either ipv4 or ipv6) along with a set of flag options 
// It then returns true/false if the IP is valid.
// Keep in mind that this checks valid format, not its actual existence

function isValidIP($ip, array $flags = []) {
    $accepted_flags = ['IPV4', 'IPV6', 'NO_PRIV_RANGE', 'NO_RES_RANGE'];
    $orFlags = 0;

    foreach ($flags as $flag) {
        $flag = strtoupper($flag);
        if (in_array($flag, $accepted_flags)) {
            $orFlags |= constant('FILTER_FLAG_' . $flag);
    return (filter_var($ip, FILTER_VALIDATE_IP, $orFlags) !== false);

Posted: March 18, 2023

Return to the snippets listing