Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP Address Validation Help

I am using this IP Validation Function that I came across while browsing, it has been working well until today i ran into a problem.

For some reason the function won't validate this IP as valid: 203.81.192.26

I'm not too great with regular expressions, so would appreciate any help on what could be wrong.

If you have another function, I would appreciate if you could post that for me.

The code for the function is below:

public static function validateIpAddress($ip_addr)
{
    global $errors;

    $preg = '#^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}' .
            '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$#';

    if(preg_match($preg, $ip_addr))
    {
        //now all the intger values are separated
        $parts = explode(".", $ip_addr);

        //now we need to check each part can range from 0-255
        foreach($parts as $ip_parts)
        {
            if(intval($ip_parts) > 255 || intval($ip_parts) < 0)
            {
                $errors[] = "ip address is not valid.";
                return false;
            }

            return true;
        }

        return true;
    } else {
        $errors[] = "please double check the ip address.";
        return false;
    }
}
like image 701
Zubair1 Avatar asked Nov 30 '22 18:11

Zubair1


2 Answers

I prefer a simplistic approach described here. This should be considered valid for security purposes. Although make sure you get it from $_SERVER['REMOTE_ADDR'], any other http header can be spoofed.

function validateIpAddress($ip){
    return long2ip(ip2long($ip)))==$ip;
}
like image 106
rook Avatar answered Dec 02 '22 11:12

rook


There is already something built-in to do this : http://fr.php.net/manual/en/filter.examples.validation.php See example 2

<?php

if (filter_var($ip, FILTER_VALIDATE_IP)) {
    // Valid
} else {
   // Invalid
}
like image 30
greg0ire Avatar answered Dec 02 '22 09:12

greg0ire