2011-01-07 121 views
0

我有一個腳本可以將輸入表單的電子郵件提交到數據庫,我想知道在提交郵件後是否有重定向PHP腳本的方法?在腳本運行後重定向PHP

我的腳本 -

<?php 
$con = mysql_connect("localhost","User","Pass"); 
if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 

mysql_select_db("emails", $con); 

$sql="INSERT INTO mlist (email) 
VALUES 
('$_POST[email]'')"; 

if (!mysql_query($sql,$con)) 
    { 
    die('Error: ' . mysql_error()); 
    } 

mysql_close($con) 
?> 

請能有人給明確的指示,因爲我學習PHP仍。

+0

如果不產生任何輸出; `header(「Location:http://www.example.com/redirect/to/otherpage_or_samepage.php?with = different_variables「);`但要小心,如果你輸出一些東西然後發送一個不同的頭文件,你會得到一個錯誤... – acm 2011-01-07 10:19:12

回答

1

試試這個:

mysql_select_db("emails", $con); 

$sql="INSERT INTO mlist (email) VALUES ('$_POST[email]'')"; 

if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } 

mysql_close($con); 

header('Location: http://www.example.com/'); 
+0

哈哈,我們都使用example.com,偉大的思想和所有這一切 – 2011-01-07 10:16:03

+0

@jakenoble :不知道我們哪一個更具創新性:)但是如果不是最快的話,你可以告訴我的手速度更快:)) – Diablo 2011-01-07 10:18:05

0
header("Location http://www.example.com"); 

這將瀏覽器重定向到example.com,請注意,你只能用這個,如果輸出尚未發送到瀏覽器,例如,要確保你有echoprintvar_dump語句使用header()

2

用途:

$url = 'http://your.redirect.url'; 
header('Location: ' . $url); 
1

此代碼從header()手冊頁採取會重定向到另一個頁面上的同一個域,並在同一目錄下:

/* Redirect to a different page in the current directory that was requested */ 
$host = $_SERVER['HTTP_HOST']; 
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); 
$extra = 'mypage.php'; 
header("Location: http://$host$uri/$extra"); 
exit; 
3

使此重定向更進一步。標題「位置」應與302響應代碼一起使用,而不是經典的200響應代碼。 Thios響應代碼對HTTP響應是「全局」的。 302意味着'重定向'。即使沒有302響應代碼,大多數瀏覽器都會處理位置標題,但是您應該設置它(例如,可以幫助您處理響應的Ajax)。

header("Location: /foo.php",TRUE,302); 

現在更多一步。實際上,303響應代碼(see-other)是更好的重定向響應代碼。它也被稱爲重定向。這種特殊的重定向意味着你的瀏覽器並不是真正的重定向,因爲他所問的頁面在錯誤的地方,但它確實是一個重定向,因爲在POST動作之後,你需要一個新的頁面結果。

header("Location: /foo.php",TRUE,303); 

編輯:由thirtydot指出,更好的使用是絕對URL在重定向

header("Location: http://www.example.com/foo.php",TRUE,303); 

請記住,POST意味着潛在的數據變化(即GET請求should'nt暗示)。後跟303的POST是正確的方法,並且會阻止您的BACK按鈕重新發布相同的請求。

0

加送頭功能

<?php 
$con = mysql_connect("localhost","User","Pass"); 
if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 

mysql_select_db("emails", $con); 

$sql="INSERT INTO mlist (email) 
VALUES 
('$_POST[email]'')"; 

if (!mysql_query($sql,$con)) 
    { 
    die('Error: ' . mysql_error()); 
    }else{ 
header("Location: ".$_SERVER["HTTP_REFERER"]); 
} 

mysql_close($con) 
?> 

或發送的JavaScript代碼爲

<?php 
$con = mysql_connect("localhost","User","Pass"); 
if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 

mysql_select_db("emails", $con); 

$sql="INSERT INTO mlist (email) 
VALUES 
('$_POST[email]'')"; 

if (!mysql_query($sql,$con)) 
    { 
    die('Error: ' . mysql_error()); 
    }else{ 

echo "<script>"; 
    echo "window.location.href= '".$_SERVER["HTTP_REFERER"]."';"; 
echo "</script>"; 

} 

mysql_close($con) 
?>