6

Possible Duplicate:
PHP header() redirect with POST variables

I'm writing a script where form data is being submitted to another script. I want the second script to perform some error-checking on the submitted $_POST data, and if everything is okay, process the data. If the data has errors, I'm using header('Location: http://www.example.com/script.php'); to return the visitor back to the form page.

The issue I'm having is that I want the form to be sticky - fields with correct data maintain the values the user put in them. Obviously, to get those values, I need access to the $_POST array. However, this seems to be destroyed when the header() call forwards the visitor back to the form.

Is there any way to use the header Location stuff to redirect the visitor to another page, while still preserving the $_POST data?

Now I'm using like this : header('Location: http://www.example.com/add.php?id='.$id.'&name='.$name.'&code='.$code.'&desc='.$description.''); and accessing as $_GET.

For the same can I use and kind of POST in header('location: xxx')??

Community
  • 1
  • 1
Vijay
  • 55
  • 1
  • 1
  • 3

3 Answers3

15

the best way to achieve this 'sticky form' is to use a session.

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

and on the redirect page you can use them like so:

<?php
session_start();
//use $_SESSION like you would the post data
?>
Mic1780
  • 1,774
  • 9
  • 23
3

You could store the $_POST data in a session:

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

And then load the values into the inputs by loading them from the $_SESSION['submitted_data'] variable, just remember to have session_start() at the top of your error page too.

Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74
0

Use sessions for that. In the form page:

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

In a script that receives $_POST data:

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

Both scripts should be on the save domain for sessions to work. If you're using relative URI in the Location header, then everything should work fine.

sanmai
  • 29,083
  • 12
  • 64
  • 76