Checking if a POST[] variable is an IP address?
I'm making a script, in which the user needs to enter a valid IP address. How can I check that it's a valid IP address? (Doesn't need to resolve)
Basically 开发者_如何学JAVA$_POST['ip']
just needs to be between 0.0.0.0
and 255.255.255.255
If you're running PHP >= 5.2, use the Filter extension:
filter_var($ip, FILTER_VALIDATE_IP)
More info here and here.
You could also try preg_match(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, $_POST['ip'])
.
More about preg_match()
here
Also there are many patterns for validation. Choose most suitable one for you.
Update: Also about using filters. Not all servers have already PHP equal or higher, than 5.2.0. So u can check version before using them, but IMHO most logical ways would be Filters or PCRE.
- Split your "IP" string by "."
- Verify that there are four entries (octet) in the array.
- Verify: 0 <= octet <= 255
- If you want to get fancier, you can check that the IP isn't in a private network, isn't a multicast network, or isn't in the reserved space.
Edit: Use the built in PHP method if available! :)
精彩评论