重定向位置-“;警告:无法修改标头信息;


Redirect location - "Warning: Cannot modify header information"

我是PHP新手。在联系表格发送到公司电子邮件后,我正试图重定向到感谢页面。然而,我收到一条错误消息:

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.

表单确实会发送到电子邮件,代码也会验证,但重定向不起作用。就像我说的,这对我来说是新的,所以请非常具体地给出答案。感谢

<?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();
}
?>

您偶然发现了大多数PHP新手要解决的第一件事,即使用PHP设置头。

出现错误消息的原因是,为了修改PHP中的HTTP标头,必须在从PHP脚本(甚至空白)向浏览器发送任何内容之前进行修改。因此,在没有看到其余代码的情况下,我会说你试图设置它太晚了,已经在做一些事情来将输出发送到浏览器。

这是您已经进行了一些输出/contact-form-handler.php:6的行,并且您随后修改标头的尝试在这一行/contact-form-handler.php on line 37失败。如果您对浏览器at line 6的输出是有意的,那么您将不得不构建代码,因为一旦有一些输出,您就无法修改头at line 37。如果这不是故意的,请检查并尝试删除该输出。