我能确保用户在表单中输入ip地址吗?


Can I ensure that a user enters an ip address in a form

我想知道如何确保用户使用PHP在HTML表单中输入ip地址。我是PHP的新手…我知道在Python中我可以使用正则表达式。但是,我如何在PHP中实现这一点呢?

表单示例:

 <form name="form1" method="post" action="connection.php">
   <label>Login:
   <input type="text" name="ipaddress" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Enter IP Address':this.value;" value="Enter IP Adress"/>
   </label>
   <label>
   <input type="submit" value="Connect"/>
   </label>

或者您可以使用PHP的filter_var函数。

http://de3.php.net/manual/en/function.filter-var.php

然后使用FILTER_VALIDATE_IP验证输入

示例(返回Bool, TRUE/FALSE):

function isIP($ip)
{
 return filter_var($ip, FILTER_VALIDATE_IP);
}

试试这个:http://www.blog.highub.com/regular-expression/php-regex-regular-expression/php-regex-validate-ip-address/

有趣的是,在HTML5中,您可以在<input>上使用pattern="([0-9]+'xe2){3}[0-9]+"属性和正则表达式来验证该字段。

另一方面,使用PHP你也可以使用Cory发布的

您可以使用ip2long,如php手册中所述:

<?php
// make sure IPs are valid. also converts a non-complete IP into
// a proper dotted quad as explained below.
$ip = long2ip(ip2long("127.0.0.1")); // "127.0.0.1"
$ip = long2ip(ip2long("10.0.0")); // "10.0.0.0"
$ip = long2ip(ip2long("10.0.256")); // "10.0.1.0"
?>

所以,检查ip是否正确,使用以下代码(感谢Puggan Se):

<?php
function validateIP($ip) {
  return $ip == long2ip(ip2long($ip));
}
?>