Search code examples
phpphpmailer

Fatal error: Cannot redeclare PHPMailerAutoload()


I am using PHPMailer to send emails from my local host.

I have written a function which is supposed to send emails to registered users who have chosen the option to receive them. (i.e. newsletter subscription, etc)

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);
    }
}

The code that is calling the function:

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

Any idea why I'm getting this error?

Fatal error: Cannot redeclare PHPMailerAutoload()

I would also like to point out that even with this error, the function still works and the emails are being sent...

EDIT: As requested, please see below the function using 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 */
}

Solution

  • If you use

    require 'phpmailer/PHPMailerAutoload.php';

    in your function, but you call the function 2 times, it will redeclare the class. Simply use require_once() instead.

    require_once('phpmailer/PHPMailerAutoload.php');