在表单操作中使用PHP_SELF在标头重定向上丢失了PHP会话变量

时间:2010-10-14 16:25:29

标签: php forms session cookies redirect

我有一个多步形式,让我们说为了方便它是两步。第一步我想选择一个单选按钮,并根据单选按钮选择它将我带到某个页面,但我也希望选择存储在会话中。我有2页: 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(A或B)

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

当我执行此条件重定向时,不会传递Country选项。会话变量和重定向或会话变量以及PHP_SELF还有问题吗?

2 个答案:

答案 0 :(得分:4)

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

第2页:

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

或者使用include方法,只需使用一页:

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>

你应该可以在US_Products.php和CDN_Products.php上使用echo $_POST['country'],或者

答案 1 :(得分:0)

在重定向之前设置会话变量 - 帖子丢失,因为重定向本质上是一个常规的GET请求

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"); 
}