检测是否发生PHP异常并根据该异常输出Flash消息

问题描述 投票:-1回答:1

我正在使用Swiftmailer发送电子邮件,并且我目前有一个try / catch块,以根据Swift_RfcComplianceException来查看电子邮件地址是否有效。我目前捕获了该错误,并在屏幕上输出了$ e-> getMessage()错误。在电子邮件的表单提交中,我设置了一个变量,以在成功发送电子邮件时发出成功消息。

问题:如何根据我的Swiftmail文件是否捕获到异常,使用相同的Flash消息区域输出错误消息。以及如何使它出现在同一页面上?我没有使用AJAX,而是使用Page Post Back。现在,我得到的只是一个带有文本的白色屏幕,我希望错误消息是提交表单的位置。谢谢。

HTML

<?php if(isset($_SESSION['message'])):?>
            <div id="success-alert" class="alert alert-success text-center">
                <?php
                    echo $_SESSION['message'];
                    unset($_SESSION['message']);
                ?>
            </div>

        <?php elseif(isset($_SESSION['email_error'])) :?>
            <div id="success-alert" class="alert alert-success text-center">
                <?php
                    echo $_SESSION['email_error'];
                    unset($_SESSION['email_error']);
                ?>
            </div>
        <?php endif; ?>

Swiftmailer

try {
    // Create a message
    $message = (new Swift_Message($_POST['subject']))
        ->setFrom('[email protected]')
        ->setTo($finalEmailList) //Array of email address
        ->setBody($_POST['message'], 'text/html')
        ->setReplyTo('[email protected]');
} catch (Swift_RfcComplianceException $e) {
    print($e->getMessage());
}

PHP

if (isset($_POST['submit_email'])) {
        require_once 'views/Swiftmail.php';
        $_SESSION['message']= "Email Sent Successfully";
        $_SESSION['email_error'] = "Invalid Email Address Entered";
}
php html swiftmailer
1个回答
1
投票

您只需将错误消息设置行从“主要” PHP代码中移出...

session_start();
if (isset($_POST['submit_email'])) {
    require_once 'views/Swiftmail.php';
}

到您的Swiftmail.php文件...

try {
    // Create a message
    $message = (new Swift_Message($_POST['subject']))
        ->setFrom('[email protected]')
        ->setTo($finalEmailList) //Array of email address
        ->setBody($_POST['message'], 'text/html')
        ->setReplyTo('[email protected]');
    $_SESSION['message']= "Email Sent Successfully";
} catch (Swift_RfcComplianceException $e) {
    $_SESSION['email_error'] = "Invalid Email Address Entered";
}

FYI,大多数现代PHP框架都内置了Flash消息组件。

© www.soinside.com 2019 - 2024. All rights reserved.