简体   繁体   English

如何简单地验证字符串是否是 PHP 中的有效 IP?

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

Using PHP, how do I validate that a string is a valid IP?使用 PHP,如何验证字符串是有效的 IP?

Examples of valid strings:有效字符串示例:

  • 192.158.5.95 192.158.5.95
  • 121.212 121.212
  • 12.12.12.204 12.12.12.204

Examples of invalid strings:无效字符串示例:

  • 121 121
  • 10 12 12 (no dots) 10 12 12(无点)

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?因此,有人可以告诉我如何验证字符串是有效的 IP 吗?

Try it with filter_varfilter_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 .如果您现在有一个像foo127.0.0.bla或类似的字符串, filter_var将返回false Valid IPs like 10.1.10.10 , ::1 are considered as valid.10.1.10.10 , ::1这样的有效 IP 被认为是有效的。

Notice注意

Also you have to check on !== false , because filter_var returns the value, if it is valid and false if it isn't (eg filter_var("::1", FILTER_VALIDATE_IP) will return ::1 , not true ).您还必须检查!== false ,因为filter_var返回值,如果它有效,则返回false (例如filter_var("::1", FILTER_VALIDATE_IP)将返回::1而不是true )。

Flags标志

You could also use some of the following flags:您还可以使用以下一些标志:

FILTER_FLAG_IPV4 (Filter for IPV4) FILTER_FLAG_IPV4(IPV4 过滤器)

FILTER_FLAG_IPV6 (Filter for IPV6) FILTER_FLAG_IPV6(IPV6 过滤器)

FILTER_FLAG_NO_PRIV_RANGE (Disallow IPs from the private range) FILTER_FLAG_NO_PRIV_RANGE(禁止私有范围内的 IP)

FILTER_FLAG_NO_RES_RANGE (Disallow IPs from the reserved range) FILTER_FLAG_NO_RES_RANGE(禁止保留范围内的 IP)

filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)

If $ip is 127.0.0.1 the function will return false .如果$ip127.0.0.1 , function 将返回false

Notice Awkwardly ::1 is ok for FILTER_FLAG_NO_PRIV_RANGE , but 127.0.0.1 isn't.注意尴尬::1对于FILTER_FLAG_NO_PRIV_RANGE是可以的,但127.0.0.1不是。

$valid = ip2long($ip) !== false;

Just in case there's anyone that doesn't want to use the ip2long function, here is a simple function (Idea taken from a class in osTicket):以防万一有人不想使用 ip2long function,这里有一个简单的 function(取自 class 中的想法)

function is_ip( $ip = null ) {

    if( !$ip or strlen(trim($ip)) == 0){
        return false;
    }

    $ip=trim($ip);
    if(preg_match("/^[0-9]{1,3}(.[0-9]{1,3}){3}$/",$ip)) {
        foreach(explode(".", $ip) as $block)
            if($block<0 || $block>255 )
                return false;
        return true;
    }
    return false;
}
<?php
$ip = "192.168.0.1";    
if(filter_var($ip, FILTER_VALIDATE_IP))
{
  echo "IP is valid";
} else
{
  echo "IP is not valid";
}
?> 

If @Tomgrohl brought up regexes, you can do it in one line:如果@Tomgrohl 提出了正则表达式,您可以在一行中完成:

function is_ip($ip) {
    return is_string($ip) && preg_match('/^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5][0-5])\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5][0-5])\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5][0-5])\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5][0-5])$/');
}

Explanation:解释:

/ // regex delimiter
    ( // start grouping
        [0-9] // matches from 0 to 9
        | // or
        [1-9][0-9] // matches from 10 to 99
        | // or
        1[0-9]{2} // matches from 100 to 199
        | // or
        2[0-5][0-5] // matches from 200 to 255
    ) stop grouping
    \. // matches the dot
    // the rest (same) of the numbers
/ regex delimiter

Online tester: https://regex101.com/r/eM4wB9/1在线测试仪: https://regex101.com/r/eM4wB9/1
Note: it only matches ipv4注意:它只匹配 ipv4

iNaD ist right, the filter_var() version is the best one - ip2long() is really not that failsave. iNaD 是对的,filter_var() 版本是最好的版本 - ip2long()确实不是那种故障保存。 Just try to put in some strange things and see for yourself.试着放入一些奇怪的东西,自己看看。 I did a performace-check and filter_var is pretty much faster than the common regex versions.我进行了性能检查,filter_var 比常见的正则表达式版本快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM