2014-11-25 75 views
6

這個contact.php表單正在處理一個提交,然後重定向到一個新的頁面,然後突然停止工作。我曾嘗試添加錯誤處理,並將標題移至所有其他頂部的頂部,但都無效。表單仍然按預期提交數據,只是重定向不起作用。任何想法,將不勝感激。PHP中不使用標頭方法重定向

<?php 
    include 'config.php'; 
    $post = (!empty($_POST)) ? true : false; 
    if($post) 
    { 
    $email = trim($_POST['email']); 
    $subject = "Downloaded Course Units"; 
    $error = ''; 
    if(!$error) 
    { 
    $mail = mail(WEBMASTER_EMAIL, $subject, $message, 
     "From: ".$email."\r\n" 
     ."Reply-To: ".$email."\r\n" 
     ."X-Mailer: PHP/" . phpversion()); 
    if($mail) 
    { 
    echo 'OK'; 
    header('location: http://www.google.com.au/'); 
    exit(); 
    } 
    } 
    } 
    ?> 
+0

請刪除exit(); – 2014-11-25 09:55:25

+0

你可能會發現這有用: - > http://stackoverflow.com/questions/768431/how-to-make-a-redirect-in-php – 2014-11-25 09:55:50

+0

PHP頭是正確的方式來做到這一點。 Javascript/Meta標籤並不可靠。刪除回聲'OK';行(和任何其他頁面輸出生成線),否則標題重定向將無法正常工作(除非您在php.ini中有輸出緩衝)... exit()是必需的,否則腳本執行將繼續! – 2014-11-25 12:00:01

回答

2

header include not,include,echo。 再次嘗試不包括,回聲。 而不是函數頭 使用

echo '<meta http-equiv="refresh" content="0; URL=http://www.google.com.au/">'; 
14

使用JavaScript代碼或。

而不是

header('location: http://www.google.com.au/'); 

使用,

?> 
<script type="text/javascript"> 
window.location.href = 'http://www.google.com.au/'; 
</script> 
<?php 

會重定向即使事情是在你的瀏覽器輸出。

但是,一個預防措施是:Javascript重定向將重定向您的網頁,即使有什麼打印在頁面上。

確保它不會跳過用PHP編寫的任何邏輯。

1
If you want to redirect to another page after html code then use 
location.href javascript method. 

參考這個簡單的代碼

<html> 
    <head> 
    <title> Using the href property of the Location object</title> 
    </head> 
    <body> 
    <script language="JavaScript"> 
    <!-- 
    function show(){ 
     document.location.href ="http://www.java2s.com"; 
    } 
    --> 
    </script> 
    <form name="form1"> 
    <br> 
    <input type="button" name="sethref" value="Set href" onClick='show()'> 
    <br> 
    </form> 
    </body> 
    </html> 
9

替換爲以下代碼header('location: http://www.google.com.au/');線在PHP重定向,而不使用頭功能。

$URL="http://yourwebsite.com/"; 
echo "<script type='text/javascript'>document.location.href='{$URL}';</script>"; 
echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $URL . '">'; 

如果你想知道的是爲什麼我都用了Meta標記和JavaScript重定向,那麼答案很簡單。

如果JavaScript在瀏覽器中被禁用,則元標記將重定向頁面。

+1

然後你應該在HTML META之前放置javascript。因爲JS可以被禁用而不是HTML!不是嗎? – 2016-10-12 01:11:02

+0

它正在工作,但每次頁面經常刷新時常。 – Sarfaraj 2018-01-18 11:17:49