PHP原生函数判断IP格式是否正确
一般我们都是通过正则表达式来判断IP格式是否正确,其实从php5.2.0之后,PHP就有专门的函数来做这个判断了。
filter_var — 使用特定的过滤器过滤一个变量
过滤器预定义常量见:http://wangxinyang.cn/wxy/view.asp?id=253
判断是否是合法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 }
以上转自:https://www.haibakeji.com/archives/313.html
/**
* 是否有效ipv4地址
*/
function is_ip($str){
return preg_match("/^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/", (string)$str) === 1 ? TRUE : FALSE;
}
/**
* 是否有效ipv6地址
* 1、可以是纯IPv6地址,如 fb80::86e2:c6f7:c749:2d43
* 2、可以是嵌入IPv4的IPv6地址,如 fb80::86e2:c6f7:c749:2d43:192.168.1.1
* 3、不能是带网卡interface标识的IPv6地址,如 fb80::86e2:c6f7:c749:2d43%15
* 4、$_SERVER['REMOTE_ADDR'] 获取的可能是3中所指的带网卡标识的IPv6,所以在判断前要先去掉网卡标识部分
*/
function is_ipv6($str){
return preg_match("/^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:)|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}(:[0-9A-Fa-f]{1,4}){1,2})|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){1,3})|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){1,4})|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){1,5})|([0-9A-Fa-f]{1,4}:(:[0-9A-Fa-f]{1,4}){1,6})|(:(:[0-9A-Fa-f]{1,4}){1,7})|(([0-9A-Fa-f]{1,4}:){6}(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){5}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}: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