PHP session variables lost on header redirect usin

2019-05-24 11:18发布

问题:

I have a multi-step form, let's say for the sake of ease it's 2 steps. First step I want to select a radio button and based on that radio button selection it takes me to a certain page, but I also want that selection stored in a session. I have 2 pages: page1.php

session_start();

if(isset($_POST['post'])) {
if (($_POST['country'] == 'US')) {
header("Location: US_Products.php"); }
elseif (($_POST['country'] == 'CDN')) {
header("Location: CDN_Products.php"); }
else { die("Error"); }
exit;
}
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="USA">USA:</label>
<input type="radio" name="country" value="US">
<label for="CDN">Canada:</label>
<input type="radio" name="country" value="CDN">
<input type="submit" name="post" value="Go To Filter">
</form>

Page2.php (either A or B)

session_start();
$_SESSION['country'] = $_POST['country'];
<?php echo $_SESSION['country']; ?>

The Country choice is not being passed when I have it do this conditional redirect. Is there a problem with session variables and redirects or session variables and PHP_SELF or something?

回答1:

Page 1:

session_start();

if(isset($_POST['post'])) {
    $_SESSION['country'] = $_POST['country'];
    if (($_POST['country'] == 'US')) {
        header("Location: US_Products.php"); }
    elseif (($_POST['country'] == 'CDN')) {
        header("Location: CDN_Products.php"); }
    else { die("Error"); }
    exit;
}
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="USA">USA:</label>
<input type="radio" name="country" value="US">
<label for="CDN">Canada:</label>
<input type="radio" name="country" value="CDN">
<input type="submit" name="post" value="Go To Filter">
</form>

Page 2:

session_start();
<?php echo $_SESSION['country']; ?>

Or using include method, just use one page:

session_start();

if(isset($_POST['post'])) {
    if (($_POST['country'] == 'US')) {
        include("US_Products.php"); }
    elseif (($_POST['country'] == 'CDN')) {
        include("CDN_Products.php"); }
    else { die("Error"); }
    exit;
}
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="USA">USA:</label>
<input type="radio" name="country" value="US">
<label for="CDN">Canada:</label>
<input type="radio" name="country" value="CDN">
<input type="submit" name="post" value="Go To Filter">
</form>

and you should be able to use echo $_POST['country'] on US_Products.php and CDN_Products.php, or



回答2:

Set the session variable before you redirect - the post is lost, as the redirect is essentially a regular GET request

if (($_POST['country'] == 'US')) 
{
  $_SESSION['country'] = $_POST['country'];
  header("Location: US_Products.php"); 
}
elseif (($_POST['country'] == 'CDN')) 
{
  $_SESSION['country'] = $_POST['country'];
  header("Location: CDN_Products.php"); 
}
else 
{ 
  die("Error"); 
}