PHP Header Location

6
我正在撰写一个脚本,其中表单数据被提交到另一个脚本。我希望第二个脚本对提交的 $_POST 数据进行一些错误检查,如果一切正常,则处理数据。如果数据有误,我将使用 header('Location: http://www.example.com/script.php'); 将访问者返回到表单页面。
我的问题是,我希望表单是黏性的 - 具有正确数据的字段保持用户输入的值。显然,为了获取这些值,我需要访问 $_POST 数组。但是,当 header() 调用将访问者转回表单时,似乎会销毁该数组。
是否有任何方法可以使用 header Location 来重定向访问者到另一个页面,同时仍保留 $_POST 数据?
现在我是这样使用的:header('Location: http://www.example.com/add.php?id='.$id.'&name='.$name.'&code='.$code.'&desc='.$description.''); 并通过$_GET访问。
那么,我能否在header('location: xxx')中使用任何POST?

http://www.php.net/manual/en/book.session.php - DaveRandom
在重定向之前,您可以手动设置$_POST - Havelock
为什么不设置会话变量来存储帖子数据呢? - kushalbhaktajoshi
5
@Havelock,我甚至不知道从何处开始描述整个威胁是多么的错误。;-( - deceze
3个回答

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
?>

注意:只有在同一服务器上才能正常工作。 - Paulo Bueno

3
您可以将$_POST数据存储在会话中:
session_start();
$_SESSION['submitted_data'] = $_POST;

然后通过从$_SESSION ['submitted_data'] 变量中加载它们,将值加载到输入中,只需记得在错误页的顶部也要有session_start()


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');

为了使会话正常工作,两个脚本应该在同一个域上。如果在Location头中使用相对URI,则一切都应该正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接