Home >php教程 >php手册 >php检查验证IP为有效IP地址函数

php检查验证IP为有效IP地址函数

WBOY
WBOYOriginal
2016-05-25 16:54:261825browse

在php5.2之前如果我们要验证IP地址是否有效我们需要使用正则来验证这样只是IP地址是不是合法的,如果要有效我们需要调用ping来操作,但php5.2.0之后,有专门的函数来做这个判断了,下面我来总结一下这些函数

判断是否是合法IP

if(filter_var($ip, FILTER_VALIDATE_IP)) {// it's valid
}else {// it's not valid
}

判断是否是合法的IPv4 IP地址

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {// it's valid
}else {// it's not valid
}

判断是否是合法的公共IPv4地址,192.168.1.1这类的私有IP地址将会排除在外

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) {// it's valid
}else {// it's not valid
}

判断是否是合法的IPv6地址

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {// it's valid
}else {// it's not valid
}

判断是否是public IPv4 IP或者是合法的Public IPv6 IP地址

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {// it's valid
}else {// it's not valid
}

如果你的php版本过低可以上面的函数都无法使用但我们可以使用正则表达试来验证

<?php
//判断IP格式
function is_ip($gonten) {
    $ip = explode(".", $gonten);
    for ($i = 0; $i < count($ip); $i++) {
        if ($ip[$i] > 255) {
            return (0);
        }
    }
    return ereg("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$", $gonten);
}
?>


本文链接:

收藏随意^^请保留教程地址.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn