我有一个问题做我的形式。当我点击按钮生成,我试图重定向到一个错误的页面,但它仍然重定向到正确的页面,即使在它是空的形式。
if(isset($_POST['Generate'])) {
if(!empty($_POST['aid'])) {
$gen_link = "www.correctlink.com";
$_SESSION['active'] = $aid;
header("Location: http://$gen_link") ;
} else {
header("Location : http://error404.com");
}
}
即使当我点击生成按钮,它仍然重定向到www.correctlink.com我想让用户在表单
中输入一些东西形式代码:
<input type="text" name="aid" id="aid" value="Enter Your Active Here" onfocus=" if (this.value == 'Enter Your Active Here') { this.value = ''; }" onblur="if (this.value == '') { this.value='Enter Your Active Here';} "/><br /><br />
<input type="submit" class="button" value="Generate" name="Generate" id="Generate"/>
这里的问题是你在文本框中设置了默认值"Enter Your Active here "。如果用户只是提交表单,甚至没有尝试在文本框中输入任何内容,则$_POST['aid']
的值变为"enter Your Active Here"。
那你怎么办呢?很简单,不检查empty
,检查
if($_POST['aid'] != "Enter Your Active Here" && ! empty(trim($_POST['aid'])))
另一个解决方案是使用占位符,但由于这是HTML5的功能,跨浏览器的兼容性是有限的。
编辑:添加第二个条件是为了确保代码在客户端机器上禁用javascript并且用户恶意地试图通过清空文本框如果您在表单中设置了value
属性,它将提交该值,因此它不会为空。而不是检查它是否为空,检查它是否等于Enter Your Active Here
。如果需要占位符文本,可以使用属性placeholder
而不是value
。
$_POST['aid']
不是空的,因为您将value
设置为Enter Your Active Here
像这样写
<input type="text" name="aid" id="aid" placeholder="Enter Your Active Here" .......
或
<label>Enter Your Active Here</label><input type="text" name="aid" id="aid" .....
replace
if(!empty($_POST['aid']))
if($_POST['aid']!="" && $_POST['aid']!="Enter Your Active Here")
谢谢。