IP Verification Help

I use this IP verification feature that I encountered while browsing, it works well until today I ran into a problem.

For some reason, the function will not check this IP as valid: 203.81.192.26

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

If you have another feature, I would appreciate it if you could post this 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; } } 
+4
source share
4 answers

Well, why do you do both regular and internal comparisons? You double check the address. Also, your second check is invalid, as it will always return true if the first octet is valid (you have a true value inside the foreach loop).

You can do:

 $parts = explode('.', $ip_addr); if (count($parts) == 4) { foreach ($parts as $part) { if ($part > 255 || $part < 0) { //error } } return true; } else { return false; } 

But as others have suggested, ip2long / long2ip can best suit your needs ...

+1
source

There is already something built-in for 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 } 
+8
source

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

 function validateIpAddress($ip){ return long2ip(ip2long($ip)))==$ip; } 
+8
source

Have you tried using the built-in functions to verify and verify the address? For example, you can use ip2long and long2ip to convert the human readable IP address to the number that it represents, then back. If the strings are identical, the IP address is valid.

There is also a filter extension that has an IP check option . The filter is enabled by default in PHP 5.2 and higher.

+4
source

Source: https://habr.com/ru/post/1312782/


All Articles