-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 protected]'; 
    $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">
4

1 Answer 1

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 protected]'; 
    $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>
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why not $emailSent = mail($emailTo, $subject, $body, $headers);
Thanks Baraa H. I did that but the redirect didn't work still. The rest of the page just stopped showing up. Any suggestions?
Hey @Fishin'Musician, can you post your updated code in the question and then I'll take another look for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.