Home > Article > Backend Development > PHP method to determine whether the IP is a valid IP address PHP example
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 }
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 }
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!