PHP注册表单验证不显示且直接跳转registered.php问题求助
问题排查及修复方案
1. 核心逻辑错误:跳转条件位置错误
你当前的跳转逻辑header("location:registered.php");仅和最后一个「两次密码是否一致」的if配对,也就是说只要两次输入的密码相等,不管前面的姓名、邮箱、密码是否为空,都会直接跳转,这是你留空表单也直接跳转的最主要原因。
正确逻辑应该是:所有验证都没有任何错误的时候,才能执行跳转。
2. 确认密码输入框配置错误
你表单里的确认密码输入框代码有两处问题:
<input type="password2" class="p-2 border rounded" placeholder="Confirm password">
- type属性错误,密码输入框的type应为
password,password2不是合法的输入框类型 - 缺失
name="password2"属性,PHP无法接收该字段的提交值,$_POST['password2']永远为空,会导致密码一致性判断永久失效。
3. empty()函数用法错误
姓名验证的代码写法不符合语法要求:
if(empty($_POST["first-name"] || $_POST["last-name"]))
empty()不能直接包裹逻辑运算表达式,你当前的写法是先计算$_POST["first-name"] || $_POST["last-name"]的布尔结果,再把这个布尔值传给empty()判断,完全达不到「姓或名为空就报错」的效果。
正确写法应该分别判断两个字段是否为空:
if(empty($_POST["first-name"]) || empty($_POST["last-name"]))
修复后的完整代码示例
头部PHP验证代码
<?php $name_error = ""; $pass_error = ""; $email_error = ""; $pass2_error = ""; // 标记是否存在验证错误 $has_error = false; if(isset($_POST['register'])) { // 验证姓名 if(empty($_POST["first-name"]) || empty($_POST["last-name"])) { $name_error = "请输入您的姓名"; $has_error = true; } // 验证邮箱 if(empty($_POST['email'])) { $email_error = "请输入邮箱地址"; $has_error = true; } // 验证密码 if(empty($_POST['password'])) { $pass_error = "请输入密码"; $has_error = true; } // 验证确认密码 if(empty($_POST['password2'])) { $pass2_error = "请输入确认密码"; $has_error = true; } elseif($_POST['password2'] != $_POST['password']){ $pass2_error = "两次输入的密码不一致"; $has_error = true; } // 所有验证通过才跳转 if(!$has_error) { header("location:registered.php"); exit; // 跳转后终止后续代码执行 } } ?>
修复后的确认密码输入框代码
<div class="my-2 p-1"> <input type="password" class="p-2 border rounded" name="password2" placeholder="Confirm password"> </div>
内容的提问来源于stack exchange,提问作者Edberaga
相关产品推荐
相关产品推荐

