You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:09:00