DSKyo DSKyo - 2 months ago 18
PHP Question

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 */
}

Answer

After much testing, the solution I have found is adding the header redirect into the function and removing it from the calling code:

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

Also, as pointed out by honerlawd, require_once is needed in order for this to work, otherwise it will send an email only to the first account found in the database. Without redirecting to the email_users.php?success, this will cause an infinite loop, no matter if I call require_once or require.

Would this be the correct approach or is it just a temporary messy fix?