PHPMailer 表单在正确的电子邮件后发送,而不会停止检查仍然为空的字段

PHPMailer form sends after correct email without stopping to check fields that are still empty

我正在尝试使用 PHPMailer 开发一个联系表单,并为此问题在服务器端进行验证。 (javascript 稍后将进行验证)。

所以我添加了 post 变量并按顺序为每个字段验证空字段。

当输入的名称和电子邮件正确输入时,它会成功验证,但是当我按提交测试主题和消息字段是否为空时,它会在验证主题和消息字段。

不知何故,当它在成功时抛出电子邮件的 catch 异常时,它会发送表单而忽略表单的其余部分。

我正在学习教程,但对于为什么会出现这种情况,我没有可靠的答案。

任何想法都会有很大帮助。

P.S。隐藏的 phone 输入字段用于蜜罐。

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>

<body>
<div class="content">
    <?php

    // Import PHPMailer classes into the global namespace
    // These must be at the top of your script, not inside a function
    use phpmailer\phpmailer\PHPMailer;
    use phpmailer\phpmailer\SMTP;
    use phpmailer\phpmailer\Exception;

    require 'phpmailer/Exception.php';
    require 'phpmailer/PHPMailer.php';
    require 'phpmailer/SMTP.php';

    if (empty($_POST['phone'])) {
        if (isset($_POST['sendmail'])) {

            $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
            $email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
            $subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
            $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

            if (empty($name)) {
                echo '<p class="error">Please enter your name</p>';
            }

            if (empty($email)) {
                echo '<p class="error">Please enter your email</p>';
            }

            if (empty($subject)) {
                echo '<p class="error">Please enter your subject</p>';
            }

            if (empty($message)) {
                echo '<p class="error">Please enter your message</p>';
            }

            // Instantiation and passing `true` enables exceptions
            $mail = new PHPMailer(true);

            try {
                //Server settings
                //$mail->SMTPDebug = SMTP::DEBUG_SERVER;                                    // Enable verbose debug output
                $mail->isSMTP();                                                                                    // Send using SMTP
                $mail->Host       = 'smtp.gmail.com';                       // Set the SMTP server to send through
                $mail->SMTPAuth   = true;                                                                   // Enable SMTP authentication
                $mail->Username   = 'email';                                // SMTP username
                $mail->Password   = 'password';                                         // SMTP password
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;             // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
                $mail->Port       = 587;                                                                    // TCP port to connect to

                //Recipients
                $mail->setFrom('email', 'Custom Form');
                $mail->addAddress($email, $name);                                                   // Add a recipient

                $mail->addReplyTo('email');

                // Attachments
                //$mail->addAttachment('/var/tmp/file.tar.gz');                     // Add attachments

                // body content
                $body = "<p>Enquiry from: " . ucwords($name) . "<br> Message: " . $message . "</p>";

                // Content
                $mail->isHTML(true);
                $mail->Name = 'Website enquiry from:' . $name;                      // Set email format to HTML
                $mail->Subject = $subject;
                $mail->Body = $body;
                $mail->AltBody = strip_tags($body);

                $mail->send();
                echo '<p class="success">Your message has been sent!</p>';
            } catch (Exception $e) {
                echo "<p class='error'>Message could not be sent. <br> Mailer Error: {$mail->ErrorInfo}</p>";
            }
        }
    }
    ?>
    <!-- <p class="success">Your message has been sent!</p>
        <p class="error">Message could not be sent. Mailer Error: </p> -->
    <form role="form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="text" id="name" name="name" placeholder="Enter your name">
        <input type="email" id="email" name="email" placeholder="Enter your email">
        <input type="text" id="subject" name="subject" placeholder="Enter subject line" maxlength="50">
        <textarea type="textarea" id="message" name="message" placeholder="Your Message Here" maxlength="6000" rows="4">Test mail using PHPMailer</textarea>
        <input type="hidden" name="phone">
        <button type="submit" name="sendmail">Send</button>
    </form>
</div>

我快速浏览了上面的内容并稍微重构了它,以便将处理过程中发现的错误记录到一个 errors 数组中 - 如果该数组不为空,则不会发送邮件。这仍然未经测试,但我希望能说明一种可能采用的方法,以确保用户提供了必要的数据

<?php

    $errors=array();
    $status=false;

    if( $_SERVER['REQUEST_METHOD']=='POST' && empty( $_POST['phone'] ) ) {
        if( isset( 
            $_POST['sendmail'],
            $_POST['name'],
            $_POST['email'],
            $_POST['subject'],
            $_POST['message']
        ) ) {
            $args=array(
                'name'      =>  FILTER_SANITIZE_STRING,
                'email'     =>  FILTER_SANITIZE_EMAIL,
                'subject'   =>  FILTER_SANITIZE_STRING,
                'message'   =>  FILTER_SANITIZE_STRING
            );
            $_POST=filter_input_array( INPUT_POST, $args );
            extract( $_POST );

            $email=filter_var( $email, FILTER_VALIDATE_EMAIL );


            if( empty( $name ) )$errors[]='Please enter your name';
            if( empty( $email ) )$errors[]='Please enter a valid email address';
            if( empty( $subject ) )$errors[]='Please enter your subject';
            if( empty( $message ) )$errors[]='Please enter your message';

            if( empty( $errors ) ){
                use phpmailer\phpmailer\PHPMailer;
                use phpmailer\phpmailer\SMTP;
                use phpmailer\phpmailer\Exception;

                require 'phpmailer/Exception.php';
                require 'phpmailer/PHPMailer.php';
                require 'phpmailer/SMTP.php';   


                // Instantiation and passing `true` enables exceptions
                $mail = new PHPMailer(true);

                try {
                    //Server settings
                    //$mail->SMTPDebug = SMTP::DEBUG_SERVER;                    // Enable verbose debug output
                    $mail->isSMTP();                                            // Send using SMTP
                    $mail->Host       = 'smtp.gmail.com';                       // Set the SMTP server to send through
                    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
                    $mail->Username   = 'email';                                // SMTP username
                    $mail->Password   = 'password';                             // SMTP password
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
                    $mail->Port       = 587;                                    // TCP port to connect to

                    //Recipients
                    $mail->setFrom('email', 'Custom Form');
                    $mail->addAddress($email, $name);                           // Add a recipient

                    $mail->addReplyTo('email');

                    // body content
                    $body = "<p>Enquiry from: " . ucwords($name) . "<br> Message: " . $message . "</p>";

                    // Content
                    $mail->isHTML(true);
                    $mail->Name = 'Website enquiry from:' . $name;               // Set email format to HTML
                    $mail->Subject = $subject;
                    $mail->Body = $body;
                    $mail->AltBody = strip_tags($body);

                    $status=$mail->send();
                } catch (Exception $e) {
                    $errors[]="<p class='error'>Message could not be sent. <br> Mailer Error: {$mail->ErrorInfo}</p>";
                }
            }
        }
    }
?>
<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="content">
            <?php
                if( $_SERVER['REQUEST_METHOD']=='POST' ){
                    if( !empty( $errors ) ){
                        foreach( $errors as $error )printf('<p class="error">%s</p>', $error );
                    }
                    if( $status ){
                        echo '<p class="success">Your message has been sent!</p>';
                    }
                }
            ?>  
            <form role="form" method="post">
                <input type="text" id="name" name="name" placeholder="Enter your name">
                <input type="email" id="email" name="email" placeholder="Enter your email">
                <input type="text" id="subject" name="subject" placeholder="Enter subject line" maxlength="50">
                <textarea id="message" name="message" placeholder="Your Message Here" maxlength="6000" rows="4">Test mail using PHPMailer</textarea>
                <input type="hidden" name="phone">
                <button type="submit" name="sendmail">Send</button>
            </form>
        </div>
    </body>
</html>