0

I have a form on my site which submits to PHP using POST. Among other things, PHP then sends a mail using PHPMailer with SMTP. Determining if the mail was successful is done using $success = $mail->send();. Then based on that result, I want to save certain details in a cookie.

When I come to set the cookie with setcookie($cName, $cVal, time()+(60*60*24*365), "/", "", 0);, I get the error telling me Cannot modify header information - headers already sent by...

PHPMailer works as expected - an email is sent. When I comment out the PHPMailer line, setcookie() works as expected - a cookie is set. I'm guessing that both PHPMailer and setcookie() automatically send headers back to the client.

Is there an option in PHPMailer that will send the mail without writing headers back to the client? I thought perhaps $mail->SMTPDebug = 2; might be causing the header to be sent but I changed it to 0 and still the same issue.

Can I get setcookie() to only update the header information and not actually send the header?

Basically, I want PHP to perform all its actions before any headers are sent back to the client. Can I take control of when the headers are sent back? ...and while we're at it, the actual information that's sent back?

Baddie
  • 305
  • 1
  • 3
  • 11
  • Sending mail does not send content to the browser. You likely have whitespace somewhere at the beginning or end of one of your files. The error will tell you exactly which file and which line is sending content. It really couldn't be much clearer. – Mike Sep 18 '18 at 00:47
  • @Mike It says that output started on the `$mail->send()` line and the error occurs on the `setcookie()` line. When I comment out the mail line, the setcookie() line works just fine. – Baddie Sep 18 '18 at 07:18
  • I was fiddling around with the code and the problem seems to have fixed itself as far as my OP is concerned. Not sure what I did so can't help answer this for anyone else. That said, I have a new problem now where `$success = setcookie(...);` returns `true` indicating it was successful, but the cookie itself doesn't update. Refreshing the page makes no difference, the cookie is not updated. But I suppose that's another question now. – Baddie Sep 18 '18 at 07:57

0 Answers0