开发者

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.


  1. Split your "IP" string by "."
  2. Verify that there are four entries (octet) in the array.
  3. Verify: 0 <= octet <= 255
  4. 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! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜