Method for php to Judge IP as Valid IP Address
- 2021-09-11 19:35:59
- OfStack
When most people read this log, their first impression must be that they want to talk about how to judge by regular expressions.
No, after php 5.2. 0, there are special functions to make this judgment.
Judge whether it is legal IP
if(filter_var($ip, FILTER_VALIDATE_IP)) {
// it's valid
}
else {
// it's not valid
}
Whether it is a legal IPv4 IP address is judged
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
// it's valid
}
else {
// it's not valid
}
To determine whether it is a legitimate 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
}
Determining 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
}
Whether it is an public IPv4 IP or a legal Public IPv6 IP address is judged
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
}
Source: http://www.electrictoolbox.com/php-validate-ip-address-filter-var/
Usually, we can choose to use regular expression implementation, which can be referred to this article for details.