0

I'm new to PHP. I'm trying to redirect to a thank you page after the contact form has been sent to the company email. However, I'm getting an error message:

Warning: Cannot modify header information - headers already sent by (output started at /home/content/86/11388686/html/contact-form-handler.php:6) in /home/content/86/11388686/html/contact-form-handler.php on line 37.

The form does send to the email and the codes does validate, but the redirect is not working. Like I said this is new to me so please be very specific with answers. Thanks

<?php
/* Set e-mail recipient */
$myemail = "tsunami.transport@aol.com";

/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$subject = check_input($_POST['subject'], "Enter a subject");
$email = check_input($_POST['email']);
$message = check_input($_POST['message'], "Write your message");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "

Name: $name
E-mail: $email
Subject: $subject

Message:
$message

";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: http://www.tsunamitransport.com/contact-form-thank-you.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>

</body>
</html>
<?php
exit();
}
?>
Micha
  • 5,117
  • 8
  • 34
  • 47

2 Answers2

2

You have stumbled upon the first thing that most new people to PHP grapple with, setting headers with PHP.

The reason for the error message is that in order for you to modify HTTP headers in PHP, you must do it before anything is sent from your PHP scripts, even white space, to the browser. So without seeing the rest of your code I would say that you are trying to set it too late, something is already being done to send output to the browser.

Robert DeBoer
  • 1,715
  • 2
  • 16
  • 26
0

This is the line where you have already done some output /contact-form-handler.php:6 and your subsequent attempt of modifying the header failed at this line /contact-form-handler.php on line 37. If your output to the browser at line 6 was intentional then you will have to structure your code because once there is some output you cannot modify the header at line 37. If it was not intentional, then check and try to remove that output.

SASM
  • 1,292
  • 1
  • 22
  • 44