PHP标头位置

时间:2012-08-31 10:27:21

标签: php header

  

可能重复:
  PHP header() redirect with POST variables

我正在编写一个脚本,表单数据正在提交给另一个脚本。我希望第二个脚本对提交的$_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进行访问。

同样可以在header('location: xxx')中使用和发布一些POST吗?

3 个答案:

答案 0 :(得分: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
?>

答案 1 :(得分:2)

您可以将$_POST数据存储在会话中:

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

然后通过从$_SESSION['submitted_data']变量加载值将值加载到输入中,只需记住错误页面顶部有session_start()

答案 2 :(得分: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,那么一切都应该可以正常工作。