compile-fan
compile-fan

Reputation: 17625

How to keep all the POST information while redirecting in PHP?

header('Location: ' . $uri);

This will miss all the $_POST information.

Upvotes: 9

Views: 15144

Answers (6)

tacone
tacone

Reputation: 11441

Don't use $_SESSION as you have been suggested. Session data is shared with all other pages, including the ones open in other tabs. You may get unpredictable behaviour if you use the same trick in multiple places of your website.

An untested better code would be something like this.

session_start();
$data_id = md5( time().microtime().rand(0,100) );
$_SESSION["POSTDATA_$data_id"] = $_POST;
header('Location: ' . $uri."?data_id=$data_id");

In the next page you may retrieve the previous post like this

session_start();
$post = array();
$data_key = 'POSTDATA_'.$_GET['data_id'];
if ( !empty ( $_GET['data_id'] ) && !empty( $_SESSION[$data_key] ))
{ 
    $post = $_SESSION[$data_key];
    unset ( $_SESSION[$data_key] );
}

The code above is not tested, you may have to deal with some error before it works.

Upvotes: 18

Dutch4All
Dutch4All

Reputation: 1

I do use my own simple method.

Just think very logical! For example if you use a text attribute which you want to keep the value of, you can use:

<?php $textvalue = $_POST['textname']; ?>
<input type="text" name="textname" value="<?php echo $textvalue; ?>" />

<br />

//And if you want to use this method for a radio button, you can use:
<?php if(isset($_POST['radio1']){
  $selected = "selected";
}  ?>
<input type="radio" name="radio1" <?php echo $selected; ?> />

Upvotes: -2

xkeshav
xkeshav

Reputation: 54022

if u want to carry forward your POST data to another pages ( except the action page) then use

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

Upvotes: 9

Brian Showalter
Brian Showalter

Reputation: 4349

You could save the post data in the session, redirect, and then retrieve it back from the session.

session_start();
$_SESSION['POSTDATA'] = $_POST;
header('Location: ' . $uri);

Then in the PHP file for the new location, retrieve the post data like this:

$_POST = $_SESSION['POSTDATA'];

Upvotes: 1

Michael
Michael

Reputation: 3426

If you perform a redirect the post will be lost and a GET will occur.

You could save your POST in a SESSION or encode it in the GET (as query string)

Upvotes: 1

deceze
deceze

Reputation: 522135

Indeed, you can't redirect POST requests.

Either let your server proxy the request (i.e. make a cURL request to the other site) or create another form, fill it with hidden fields and submit it with Javascript/let the user click.

Alternatively, as @diEcho says, depending on what you're trying to do: sessions.

Upvotes: 2

Related Questions