2013-07-12 132 views
0

我是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 = "[email protected]"; 

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

回答

2

你已經偶然發現了大多數PHP新手都在用PHP設置頭文件。

錯誤消息的原因是,爲了讓您在PHP中修改HTTP標頭,您必須在PHP腳本(甚至是空白)向瀏覽器發送任何內容之前執行此操作。因此,如果沒有看到代碼的其餘部分,我會說你試圖設置它太晚,已經有一些事情將輸出發送到瀏覽器。

+0

你會推薦我把它放在顯示的代碼中?我已經移動了幾次,但似乎沒有任何工作。 – user2577683

+0

您是否嘗試過切換if語句以在電子郵件無效時先設置標題? –

0

這是您已經完成一些輸出/contact-form-handler.php:6的行,並且您後續嘗試修改標頭失敗,此行爲/contact-form-handler.php on line 37。如果您輸出到瀏覽器at line 6是故意的,那麼您將不得不構建您的代碼,因爲一旦有一些輸出,您將無法修改標頭at line 37。如果不是有意的,那麼請檢查並嘗試刪除該輸出。

相關問題