致命错误:无法重新声明 PHPMailerAutoload()

问题描述 投票:0回答:3

我正在使用 PHPMailer 从本地主机发送电子邮件。

我编写了一个函数,该函数应该向选择接收电子邮件选项的注册用户发送电子邮件。 (即新闻通讯订阅等)

function email_users($subject, $body) {
    include('core/db/db_connection.php');
    $sql = "SELECT email, first_name FROM `_users` WHERE allow_email = 1";
    $query = mysqli_query($dbCon, $sql);
    while (($row = mysqli_fetch_assoc($query)) !== false) {
        $body = "Hello ". $row['first_name'] . ", <br><br>" . $body;
        email($row['email'], $subject, $body);
    }
}

调用该函数的代码:

if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
        ?>
            <h3 class="email_success">Emails have been sent</h2>
            <a href="admin.php" class="email_success_a">Go back to the admin page</a>
        <?php 
        } else {
            if (empty($_POST) === false) {
                if (empty($_POST['subject']) === true) {
                    $errors[] = 'A message subject is required.';
                }
                if (empty($_POST['body']) === true) {
                    $errors[] = 'A body message is required.';
                }
                if (empty($errors) === false) {
                    echo output_errors($errors);
                } else {
                    email_users($_POST['subject'], $_POST['body']);
                    header('Location: email_users.php?success');
                    exit();
                }
            }
// generate email form otherwise

知道为什么我会收到此错误吗?

致命错误:无法重新声明 PHPMailerAutoload()

我还想指出,即使出现此错误,该功能仍然有效并且电子邮件正在发送......

编辑:根据要求,请参阅下面使用 PHPMailer 的功能:

function email($user, $subject, $body) {
    require 'phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;

 /* $mail -> Host,username,password and other misc stuff
    $mail->Subject = $subject;
    $mail->Body    = $body;
    $mail->AltBody = $body; etc */
}
php phpmailer
3个回答
3
投票

如果您使用

需要'phpmailer/PHPMailerAutoload.php';

在你的函数中,但是你调用该函数2次,它会重新声明该类。只需使用

require_once()
即可。

require_once('phpmailer/PHPMailerAutoload.php');

1
投票

经过多次测试,我找到的解决方案是将标头重定向添加到函数中,并将其从调用代码中删除:

function email_users($subject, $body) {
    include('core/db/db_connection.php');
    $sql = "SELECT email, first_name FROM `_users` WHERE allow_email = 1";
    $query = mysqli_query($dbCon, $sql);
    while (($row = mysqli_fetch_assoc($query)) !== false) {
        $body = "Hello ". $row['first_name'] . ", <br><br>" . $body;
        email($row['email'], $subject, $body);
        header('Location: email_users.php?success');
    }
}

此外,正如 honerlawd 所指出的,需要 require_once 才能使其工作,否则它只会向数据库中找到的第一个帐户发送电子邮件。如果不重定向到 email_users.php?success,这将导致无限循环,无论我调用 require_once 还是 require。

这是正确的方法还是只是暂时的混乱修复?


0
投票

邮件将仅发送给第一个注册用户,后续用户将不会收到邮件,因为 require 'phpmailer/PHPMailerAutoload.php' 意味着 PHPMailerAutoload() 在每次迭代中都被重新声明。

改为使用“require_once”,这样就不会重新声明该函数。

function email($user, $subject, $body) {
    require_once 'phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;
}
© www.soinside.com 2019 - 2024. All rights reserved.