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

PHP联系表单POST提交后出现$errEmail、$errMessage未定义变量错误求助

解决联系表单的未定义变量错误

你的问题出在**$errEmail和$errMessage**仅在验证失败时才被赋值,当用户输入合法内容时,这两个变量从未被声明,导致PHP抛出未定义变量警告。

修改方案

在if (isset($_POST["submit"]))代码块的开头,提前初始化这两个变量,确保无论验证结果如何,变量都存在:

<?php
    
if (isset($_POST["submit"])) {
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'Contact Form';
    $to = 'example@example.com';
    $subject = 'Message from Contact';
    // 提前初始化错误变量
    $errEmail = '';
    $errMessage = '';

    $body = " E-Mail: $email
 Message:
 $message";

    // Check if email has been entered and is valid
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errEmail = 'Please enter a valid email address';
    }

    // Check if message has been entered
    if (empty($message)) {
        $errMessage = 'Please enter your message';
    }

    // If there are no errors, send the email
    if (!$errEmail && !$errMessage) {
        if (mail ($to, $subject, $body, $from)) {
            $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
        } else {
            $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
        }
    }
}
?>

原理说明

PHP会对未声明就使用的变量抛出警告。提前初始化变量后,即使验证通过(没有触发错误赋值逻辑),变量也处于已定义状态(值为空字符串),!$errEmail和!$errMessage的判断依然有效(空字符串在布尔判断中视为false,取反后为true)。

内容的提问来源于stack exchange,提问作者CT Roots

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:25:24