I am building my first site using an MVC framework, and the view that the user sees is determined by the $_GET[‘page’] variable. If you would like to see other code I can post it, but as far as I can tell, the code that is having the problem is displayed below. I’m not sure if it makes a difference, but this code is held in a different folder from the actual form itself, and all applicable files are included via the index folder and the include() command.
I am trying to redirect the user to a different page after submitting an email form, and have tried both header() and using window.location in javascript, but I am new to PHP and cant seem to get it to work, it just submits the form and sends the email.
<?php ob_start(); $error = ""; $successMessage = ""; if ($_POST) { if (!$_POST["email"]) { $error .= "An email adress is required.<br>"; } if (!$_POST["subject"]) { $error .= "A subject is required.<br>"; } if (!$_POST["contactMessage"]) { $error .= "A message is required.<br>"; } if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) { $error .= "A valid email adress is required.<br>"; } if ($error != "") { $error = '<div class="contactFormElement infoMessage" role="alert"><p><strong>There were error(s) in your form:</strong></p>' . $error . '</div>'; } else { $emailTo = "example@example.com"; $subject = $_POST['subject']; $contactMessage = $_POST['contactMessage']; $headers .= "From: Mailer <mailer@example.com"; $headers .= " Reply-To: ".$_POST['email']; $headers .= " Return-Path: ".$_POST['email']; if (mail($emailTo, $subject, $contactMessage, $headers)) { header('Location: index.php'); exit(); } else { $error = '<div class="contactFormElement infoMessage"><p><strong>Your message was not sent. Please try again later.</strong></p></div>'; } } } ob_end_flush(); ?>
I have tried to put header() where it is currently located in the code, as well as trying this javascript in its place
echo '<script type="text/javascript"> window.location = "http://www.google.com/" </script>';
When I echo the javascript, all that it does is submit the form and display window.location = “http://www.google.com/” on the screen, it doesn’t seem to actually execute the script, and with the header() command, it just exits the page, it doesn’t redirect it.
Any help would be greatly appreciated, thank you!
Advertisement
Answer
This answer is simply for anyone looking at this question in the future. I was able to get the header();
function to work, but it required reworking how my entire site redirects between pages, so I wouldn’t take anything that is displayed here very seriously, as this is my first attempt at coding anything by myself and has a lot of flaws.