-2

I'm having a difficult time getting my page to redirect after form submission. I've followed the advice that I've been able to find so far and no luck. Any help would be greatly appreciated.

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

$subject = "CONTACT FORM";
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
    $hasError = true;
} else {
    $name = trim($_POST['contactname']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '')  {
    $hasError = true;
} else {
    $email = trim($_POST['email']);
}

//If there is no error, send the email
if(!isset($hasError)) {
    $emailTo = 'email@domain.com'; 
    $body = "Name: $name \nEmail: $email";
    $headers = 'From: Bond Limo (Newsletter Signup) <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

    mail($emailTo, $subject, $body, $headers);
    $emailSent = true;

    }
}
?>

  <?php if(isset($hasError)) { //If errors are found ?>
  <p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
  <?php } ?>
  <?php if(isset($emailSent) && $emailSent == true) { 

    header("Location: http://www.website.com");

   } 
   ?>

  <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="side-form">
SuperDJ
  • 7,488
  • 11
  • 40
  • 74

1 Answers1

1

Your header is not being processed. In order for your header to be processed and the redirect to occur, you will have to call the die() function after your header. Like so:

<?php
    if(isset($emailSent) && $emailSent) {
        header("Location: http://www.website.com");
        die();
    }
?>

Additionally, your code can be optimized by not checking:<?php if(isset($hasError)) { //If errors are found ?> again. Rather, just connect it with the above if statement and use an else statement like so:

// If there is no error, send the email
if (!isset($hasError)) {
    $emailTo = 'email@domain.com'; 
    $body = "Name: $name \nEmail: $email";
    $headers = 'From: Bond Limo (Newsletter Signup) <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

    $emailSent = mail($emailTo, $subject, $body, $headers);
} else {
    // Errors found
    <p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
}
Baraa
  • 1,341
  • 11
  • 8