Search code examples
phpemailheaderxamppphpmailer

Cannot redirect after had sent emails with PHPMailer


The problem

For a school project, I'm creating a website which simulates an e-commerce. In this site I have a page called myCart.php in which I can see what I'm going to buy.

After the click of "Buy" button, I'm sending two emails using PHPMailer: one from the e-commerce that confirms the purchase and one from the bank (because I created even a bank website). After this, I want to automatically redirect the user to the cart page.

When I do so, I achieve to send the email but I cannot redirect beacuse of this error:

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\path\to\PHPMailer\src\SMTP.php:284) in C:\xampp\htdocs\path\to\file\e-commerce\buyProducts.php on line 70

I tried to echo a string of a script to redirect, but every time I see the logs of PHPMailer for less than a second and than the cart page. This is my code:

$sql = "SELECT conti.Saldo FROM conti
        INNER JOIN carte ON(carte.Numero_carta = conti.Numero_carta)
        WHERE conti.Numero_carta = '$numero';";
if ($raw = $con->query($sql)) {
    $ris = $raw->fetch_assoc();
    $new = $ris["Saldo"] - $tot;
    $update = "UPDATE conti
               SET Saldo = '$new'
               WHERE Numero_carta = '$numero'";
    if ($con->query($update)) { 

        // invio email per visualizzazione acquisto
        if(sendEmails($tot)){
            foreach ($_SESSION["cart"] as $key => $value){
                unset($_SESSION["cart"][$key]);
            }

            header("location: myCart.php?acquistato=c");
            //echo "<script>window.location.href = \"myCart.php?acquistato=c\";</script>";
        }
    }
}

Solution

  • Here's the giveaway:

    every time I see the logs of PHPMailer for less than a second

    If you're seeing PHPMailer logs at all, you're outputting debug content, which will trigger sending headers, and then redirects can't work. Debugging is only for debugging in development. Turn it off in production:

    $mail->SMTPDebug = 0;