Home > Backend Development > PHP Tutorial > PHP method to determine whether the IP is a valid IP address PHP example

PHP method to determine whether the IP is a valid IP address PHP example

jacklove
Release: 2023-04-02 06:18:02
Original
1980 people have browsed it

This article mainly introduces the method for PHP to determine whether an IP is a valid IP address. Friends who need it can refer to it

Most people who see this log will have the first impression that it is about how to pass Regular expression to judge.

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
}
Copy after login

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
}
Copy after login

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
}
Copy after login

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
}
Copy after login

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
}
Copy after login

Source of this article: http://www.electrictoolbox.com/php-validate-ip-address-filter-var/

Normally, we can Choose to use regular expressions. For details, please refer to this article.

Related recommendations:

AES encryption class definition and usage examples implemented in php PHP skills

PHP implementation Code php tips to prevent cross-site and ##

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

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template