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

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

WBOY
Release: 2016-05-25 16:54:26
Original
1823 people have browsed it

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

判断是否是合法IP

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

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

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

判断是否是合法的公共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
}
Copy after login

判断是否是合法的IPv6地址

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

判断是否是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
}
Copy after login

如果你的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);
}
?>
Copy after login


本文链接:

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template