-1

Currently trying to create an email contact form for a personal website. The header() redirect function is not working and keeps returning the error message:

"PHP Warning: Cannot modify header information - headers already sent by (output started at /home1/claireel/public_html/email.php:1) in /home1/claireel/public_html/email.php on line 38"

Also, the form will send email to the testing email that I had originally had in the file but when I changed the address to the one I actually intend to use, it won't send.

<?php
$errors = [];
$errorMessage = '';

if (!empty($_POST)) {
   $first = $_POST['first'];
   $last = $_POST['last'];
   $email = $_POST['email'];
   $message = $_POST['message'];

   if (empty($first)) {
       $errors[] = 'First name is empty';
   }

   if (empty($last)) {
    $errors[] = 'Last name is empty';
}

   if (empty($email)) {
       $errors[] = 'Email is empty';
   } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       $errors[] = 'Email is invalid';
   }

   if (empty($message)) {
       $errors[] = 'Message is empty';
   }

   if (empty($errors)) {
       $toEmail = '************@gmail.com';
       $emailSubject = 'New email from your contact form';
       $headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=utf-8'];
       $bodyParagraphs = ["Name: {$first} {$last}", "Email: {$email}", "Message:", $message];
       $body = join(PHP_EOL, $bodyParagraphs);

       if (mail($toEmail, $emailSubject, $body, $headers)) {
           header('Location: thank-you.html');
       } else {
           $errorMessage = 'Oops, something went wrong. Please try again later';
       
       }

   } else {

       $allErrors = join('<br/>', $errors);
       $errorMessage = "<p style='color: red;'>{$allErrors}</p>";
   }
}

?>

I have made sure there is no white-space before the opening or after the closing php tags. I have also made sure the file is encoded in UTF-8 wihtout BOM. I also don't see anything in the file that would be outputting before the header function.

Bas H
  • 2,114
  • 10
  • 14
  • 23
  • “ I have made sure there is no white-space before the opening or after the closing php tags.” - the error message says the output was started on line 1, so it looks like you failed to check that properly. – Quentin Feb 13 '23 at 07:16

1 Answers1

-1

Put exit in

if (mail($toEmail, $emailSubject, $body, $headers)) {
    header('Location: thank-you.html');
} else {
    $errorMessage = 'Oops, something went wrong. Please try again later';
}

after header():

if (mail($toEmail, $emailSubject, $body, $headers)) {
    header('Location: thank-you.html');
    exit;
} else {
    $errorMessage = 'Oops, something went wrong. Please try again later';
}
  • The error occurs on the line before you propose adding an exit statement. That won’t fix the problem. – Quentin Feb 13 '23 at 07:18