【问题标题】:Why my sessions variables have been automatically unset when i redirect to then same script?为什么当我重定向到同一个脚本时我的会话变量会自动取消设置?
【发布时间】:2012-04-16 08:30:28
【问题描述】:

我在 testmysql.php 中设置了一个名为 foo 的会话变量,我再次将脚本重定向到相同的脚本,我打印会话 var 然后取消设置它.. 但是,当我已重定向..这是为什么,我该如何解决?

<?php 

session_start();

if(empty($_GET)) {
    $_SESSION['foo'] = 'bar';
    header("location:testmysql.php?redirect". '=' . 'bar');
}

var_dump( $_SESSION);
unset ($_SESSION['foo']);

【问题讨论】:

  • Location HTTP 标头仅采用绝对 URI,而不采用相对 URI。不要依赖浏览器错误恢复。

标签: php


【解决方案1】:

当你设置重定向时你并没有中止脚本,因此unset ($_SESSION['foo'])总是被执行:

<?php 

session_start();

if(empty($_GET)) {
    $_SESSION['foo'] = 'bar';
    header("location:testmysql.php?redirect". '=' . 'bar');
    exit; // <--- Missing
}

var_dump( $_SESSION);
unset ($_SESSION['foo']);

【讨论】:

    【解决方案2】:

    if 替换为if else

    if(empty($_GET)) {
        $_SESSION['foo'] = 'bar';
        header("location:testmysql.php?redirect". '=' . 'bar');
    }
    else
    {
        var_dump( $_SESSION);
        unset ($_SESSION['foo']);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-21
      • 2017-07-06
      • 2019-08-03
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 2014-03-18
      • 2019-04-12
      • 2015-03-03
      相关资源
      最近更新 更多