2014-10-05 76 views
-2

我很難讓頁面在表單提交後重定向。我遵循了迄今爲止能夠找到的建議,但沒有運氣。任何幫助將不勝感激。PHP重定向問題

<?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"> 
+0

也許你可以從這裏找到一些幫助:http://stackoverflow.com/questions/768431/how-to-make -a重定向在php中? – Suprsonic 2014-10-05 17:40:39

+0

可能重複的[我如何重定向PHP中沒有標題錯誤?](http://stackoverflow.com/questions/1255518/how-can-i-redirect-in-php-without-header-errors) – 2014-10-05 17:41:13

+0

-1不要在標題前做任何輸出。它已被問多次,請做更好的研究! – 2014-10-05 17:41:54

回答

1

您的頭文件未被處理。爲了處理標題並重定向,您必須在標題後調用die()函數。像這樣:

<?php 
    if(isset($emailSent) && $emailSent) { 
     header("Location: http://www.website.com"); 
     die(); 
    } 
?> 

此外,您的代碼可以通過不再檢查:<?php if(isset($hasError)) { //If errors are found ?>再次優化。相反,只是上面的連接,如果語句,並使用else語句,像這樣:

// 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> 
} 
+1

爲什麼不能'$ emailSent = mail($ emailTo,$ subject,$ body,$ headers);' – DanFromGermany 2014-10-05 18:03:37

+0

@DanFromGermany - 尼斯優化! :) – Baraa 2014-10-05 18:35:06

+0

感謝Baraa H.我做到了,但重定向仍然無法正常工作。頁面的其餘部分剛剛停止顯示。有什麼建議麼? – 2014-10-21 13:22:16