我可以确保用户在表单中输入IP地址

时间:2011-08-10 15:06:16

标签: php regex

我正在试图弄清楚如何确保用户使用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>

4 个答案:

答案 0 :(得分:2)

或者您可以使用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);
}

答案 1 :(得分:1)

答案 2 :(得分:1)

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

另一方面,使用PHP,您也可以使用Cory发布的内容。

答案 3 :(得分:0)

你可以使用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));
}
?>
相关问题