PHP preg_match验证失效,注册提交返回invalidusername及404错误
问题原因及修复方案
核心错误点
- invalidUsername函数逻辑完全倒置
- 邮箱校验错误调用了用户名校验规则
- 后续流程存在多处参数写错的问题
1. 修复 functions.inc.php 代码
你当前的invalidUsername函数逻辑完全相反:正则/[^A-Za-z0-9_\-]/的作用是匹配用户名中存在的非法字符(即不在大小写字母、数字、下划线、横杠范围内的字符),只要匹配到就说明用户名无效。但你的代码中如果没匹配到非法字符(也就是用户名合法),反而返回true标记为无效,导致所有合法用户名都报错。
另外需要新增单独的邮箱校验函数,不能用用户名规则校验邮箱:
function invalidUsername($username){ // 匹配到非法字符时返回true(用户名无效),未匹配到返回false(用户名合法) return preg_match("/[^A-Za-z0-9_\-]/", $username) ? true : false; } function invalidEmail($email){ // 用PHP内置过滤器校验邮箱格式 return !filter_var($email, FILTER_VALIDATE_EMAIL) ? true : false; }
2. 修复 signup.inc.php 代码
存在三个明显错误:
- 邮箱校验调用了错误的invalidUsername函数
- 用户名已存在的跳转错误提示参数写错
- createUser调用时传入了未定义的$name、$pwd变量
修复后代码:
<?php if(isset($_POST["submit"])){ $firstname =$_POST["firstname"]; $lastname =$_POST["lastname"]; $username =$_POST["username"]; $email =$_POST["email"]; $gender =$_POST["gender"]; $password =$_POST["password"]; $repeatPassword =$_POST["repeatpassword"]; require_once 'dbh.inc.php'; require_once 'functions.inc.php'; if (emptyInputSignup($firstname, $lastname, $username, $email, $gender, $password, $repeatPassword ) !==false){ header("location:../signup.php?error=emptyinput"); exit(); } if (invalidUsername($username) !==false){ header("location:../signup.php?error=invalidusername"); exit(); } // 修复:调用单独的邮箱校验函数 if (invalidEmail($email) !==false){ header("location:../signup.php?error=invalidemail"); exit(); } if (passwordMatch($password, $repeatPassword) !==false){ header("location:../signup.php?error=passworddontmatch"); exit(); } // 修复:错误提示改为用户名已存在 if (usernameExists($con, $username) !==false){ header("location:../signup.php?error=usernametaken"); exit(); } // 修复:传入正确的参数,按需拼接姓名、传入正确的密码变量 $fullName = $firstname . ' ' . $lastname; createUser($con,$fullName,$email,$username,$password); } else { header("location:../signup.php"); exit(); }
内容的提问来源于stack exchange,提问作者HelloKitty
相关产品推荐
相关产品推荐

