Before php5.2, if we want to verify whether the IP address is valid, we need to use regular expressions to verify that the IP address is valid. If it is valid, we need to call ping, but after php5.2.0, there are special functions to make this judgment. I will summarize these functions below
Determine whether the IP address is valid
The Code is as follows: |
Copy code |
If (filter_var ($ ip, FILTER_VALIDATE_IP) {// it's valid } Else {// it's not valid } |
Determine whether an IPv4 IP address is valid
The Code is as follows: |
Copy code |
If (filter_var ($ ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) {// it's valid } Else {// it's not valid }
|
Check whether it is a legal public IPv4 address. Private IP addresses such as 192.168.1.1 will be excluded.
The Code is as follows: |
Copy code |
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 an IPv6 address is valid
The Code is as follows: |
Copy code |
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 address or a legal Public IPv6 IP Address
The Code is as follows: |
Copy code |
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 } |
If your php version is too low, the above functions cannot be used, but we can use regular expression for verification.
The Code is as follows: |
Copy code |
// Determine the IP Format Function is_ip ($ gonten ){ $ Ip = explode (".", $ gonten ); For ($ I = 0; $ I <count ($ ip); $ I ++) { If ($ ip [$ I]> 255 ){ Return (0 ); } } Return ereg ("^ [0-9] {1, 3 }. [0-9] {1, 3 }. [0-9] {1, 3 }. [0-9] {1, 3} $ ", $ gonten ); } |