Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simply validate whether a string is a valid IP in PHP?

Tags:

validation

php

Using PHP, how do I validate that a string is a valid IP?

Examples of valid strings:

  • 192.158.5.95
  • 121.212
  • 12.12.12.204

Examples of invalid strings:

  • 121
  • 10 12 12 (no dots)

My current script uses this code, but this is insufficient for my needs:

if(strpos($input, '.') !== false)
{    
  // There is a period 
} 
else 
{     
  // No Period 
} 

As such, can someone please advise how I can validate that a string is a valid IP?

like image 945
Harsh Avatar asked Apr 29 '11 03:04

Harsh


2 Answers

Try it with filter_var

Example:

if(filter_var('127.0.0.1', FILTER_VALIDATE_IP) !== false) {
    // is an ip
} else {
    // is not an ip
}

If you now have a string like foo, 127.0.0.bla or similar, filter_var will return false. Valid IPs like 10.1.10.10, ::1 are considered as valid.

Notice

Also you have to check on !== false, because filter_var returns the value, if it is valid and false if it isn't (e.g. filter_var("::1", FILTER_VALIDATE_IP) will return ::1, not true).

Flags

You could also use some of the following flags:

FILTER_FLAG_IPV4 (Filter for IPV4)

FILTER_FLAG_IPV6 (Filter for IPV6)

FILTER_FLAG_NO_PRIV_RANGE (Disallow IPs from the private range)

FILTER_FLAG_NO_RES_RANGE (Disallow IPs from the reserved range)

filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)

If $ip is 127.0.0.1 the function will return false.

Notice Awkwardly ::1 is ok for FILTER_FLAG_NO_PRIV_RANGE, but 127.0.0.1 isn't.

like image 78
theiNaD Avatar answered Sep 20 '22 14:09

theiNaD


$valid = ip2long($ip) !== false;
like image 35
zerkms Avatar answered Sep 18 '22 14:09

zerkms