2012-08-31 60 views
5

可能重複:
PHP header() redirect with POST variablesPHP頭位置

我寫字的地方表單數據被提交到另一種語言的腳本。我希望第二個腳本對提交的$_POST數據執行一些錯誤檢查,如果一切正常,請處理數據。如果數據有誤,我使用header('Location: http://www.example.com/script.php');將訪問者返回到表單頁面。

我遇到的問題是我希望表單是粘性的 - 具有正確數據的字段保持用戶放入其中的值。顯然,要獲得這些值,我需要訪問$_POST陣列。但是,當header()調用將訪問者轉回表單時,這似乎被破壞了。

有什麼辦法使用標題位置的東西來重定向訪問者到另一個頁面,同時仍然保留$_POST數據?

現在我使用的是這樣的:header('Location: http://www.example.com/add.php?id='.$id.'&name='.$name.'&code='.$code.'&desc='.$description.'');和訪問$_GET

對於同樣的我可以使用和種類POST在header('location: xxx') ??

+0

http://www.php.net/manual/en/book.session.php – DaveRandom

+0

你可以手動設置'$ _POST'(http://stackoverflow.com/questions/3418044/setting-post-變量 - 沒有使用的形式)再次重定向之前。 – Havelock

+0

爲什麼不設置會話變量來存儲發佈數據? ? – kushalbhaktajoshi

回答

2

您可以在$_POST數據存儲在一個會話:

session_start(); 
$_SESSION['submitted_data'] = $_POST; 

然後從$_SESSION['submitted_data']變量加載它們加載值到輸入,只記得你的錯誤頁面的頂部有session_start()太。

15

實現此「粘性表單」的最佳方式是使用會話。

<?php 
session_start(); 
$_SESSION = $_POST; 
//do error checking here 
//if all is valid 
session_write_close(); 
header('Location: *where you want your form to go*'); 
die; 
?> 

和重定向頁面,您可以使用它們像這樣的:

<?php 
session_start(); 
//use $_SESSION like you would the post data 
?> 
0

使用sessions了點。在表單頁:

<?php 
if (!empty($_COOKIE[session_name()])) { 
    // we only start session if there is a session running 
    session_id() || session_start(); 
} 

if (empty($_POST) && !empty($_SESSION['POST'])) { 
    // make sure you're not overwriting 
    $_POST = $_SESSION['POST']; 
} 
// and so on just like you have $_POST filled 

在接收$ _ POST數據的腳本:

<?php 
// after you're done with checking and stuff 
session_id() || session_start(); 
$_SESSION['POST'] = $_POST; 
header('Location: /script.php'); 

兩個腳本應在保存域的會話。如果您在位置標題中使用相對URI,則一切都應該正常工作。