PHP联系表单仅校验message字段忽略其他输入校验该如何修复?
问题根因
你代码的问题出在邮件发送逻辑的判断位置:你把发邮件和跳转的代码放在了message字段非空的else分支里,这就导致只要message填了,就算姓名、邮箱的校验没通过,也会直接执行发送逻辑,完全忽略其他字段的错误。
修复后的完整代码
<?php $fullName = $customerEmail = $message = ''; $errors = array('fullName' => '', 'customerEmail' => '', 'message' => ''); if (isset($_POST['submit'])) { $myEmail = "xxxxxxxxxxxxx"; $timeStamp = date("d/M/Y H:i:s"); // 修正了原错误的日期格式 $body = ""; // 加trim去除首尾空格,避免用户只打空格绕过必填校验 $fullName = trim($_POST['fullName']); $customerEmail = trim($_POST['customerEmail']); $chosenSubject = trim($_POST['subject']); $message = trim($_POST['message']); $body .= "From: " . $fullName . " at $timeStamp" . "\r\n"; $body .= "Email: " . $customerEmail . "\r\n"; $body .= "Message: " . $message . "\r\n"; if (empty($fullName)) { $errors['fullName'] = "Full name is required. <br>"; } else { if (!preg_match("/^([a-zA-Z' ]+)$/", $fullName)) { $errors['fullName'] = "Your name must be a valid name."; } } if (empty($customerEmail)) { $errors['customerEmail'] = "An email is required. <br>"; } else { if (!filter_var($customerEmail, FILTER_VALIDATE_EMAIL)) { $errors['customerEmail'] = "Email must be a valid email address."; } } if (empty($message)) { $errors['message'] = "A message is required."; } // 新增全局校验:所有字段都通过校验才发邮件跳转 if (empty($errors['fullName']) && empty($errors['customerEmail']) && empty($errors['message'])) { mail($myEmail, $chosenSubject, $body); header("Location: public/mail_sent.php"); exit; // 加exit终止后续代码执行,避免安全隐患 } } ?>
修复说明
- 调整了邮件发送的触发条件:不再和
message字段的校验绑定,改为判断三个字段的校验错误都为空时才发送邮件 - 给所有表单值加了
trim()处理,避免用户输入全空格绕过必填校验 - 修正了日期格式,原
date("dd/M/YY HH:i:s")会输出重复的日期字符,调整为更规范的显示格式 - 跳转后增加
exit终止代码执行,避免跳转后后续代码意外运行
内容的提问来源于stack exchange,提问作者Daniel Radosa
相关产品推荐
相关产品推荐

