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

后端 未结 6 1952
再見小時候
再見小時候 2021-01-04 03:01

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
6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-04 03:38

    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.

提交回复
热议问题