Home  >  Article  >  Backend Development  >  PHP method to determine whether it is a valid IP address

PHP method to determine whether it is a valid IP address

小云云
小云云Original
2018-01-29 09:25:565115browse

When most people see this blog, their first impression must be that it talks about how to judge through regular expressions. This article mainly introduces the method of determining whether an IP is a valid IP address in PHP. Friends who need it can refer to it. I hope it can help everyone.

No, after php5.2.0, there is a special function to make this judgment.

Judge whether it is a legal IP


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

Judge whether it is a legal IPv4 IP address


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

Determine whether it is a legal public IPv4 address. Private IP addresses such as 192.168.1.1 will be excluded


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

Determine whether it is a legal IPv6 address


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

Determine whether it is a public IPv4 IP or a legal Public IPv6 IP address


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
}

Related recommendations :

How to calculate IP address mask in php

IP address processing in PHP

php How to limit the IP address range

The above is the detailed content of PHP method to determine whether it is a valid IP address. For more information, please follow other related articles on the PHP Chinese website!

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