会话变量不可用

时间:2016-05-23 08:09:44

标签: php

我在print_r($ _ SESSION)中打印会话,它在数组后面的索引页面中显示。

 Array
(
    [name] => hhh
)

index.php

  <?php 
  session_start();
  $_SESSION['name']='hhh';

我想在任何时候取消设置此变量。所以我在同一目录中创建了一个新的php文件,其中包含以下内容

    <?php

    session_start();
    echo "before destroying the session";
    print_r($_SESSION);
    unset($_SESSION['name']);//remove the name session variable which is available in my index page.
    session_destroy(); //destroy the session
    echo "after destroying the session";
    print_r($_SESSION);

但每当我运行上面的代码时,它会打印以下内容:

before destroying the sessionArray ( ) after destroying the sessionArray ( )

为什么在上面的脚本页面中无法访问索引页面中可用的会话?

提前致谢

2 个答案:

答案 0 :(得分:0)

我不确定您的目标是什么,这就是您的代码所做的事情:

# You start your session
session_start();

# Echo a string
echo "before destroying the session";

# Print the $_SESSION array, comes out empty because you havn't put anything in the session
print_r($_SESSION);

# You unset the 'name' key in the $_SESSION array, which wasn't even there in the first place
unset($_SESSION['name']);

# You get rid of the session
session_destroy();

# Echo a string
echo "after destroying the session";

# You print $_SESSION variable again, which is going to be empty, because you just destroyed the session.
print_r($_SESSION);

我的观点解释你的代码是,你真的想做什么?

如果您想在多个页面之间使用$ _SESSION,只需在页面之间不要使用session_destroy(),只有当您的用户退出时才会将其销毁。可以这么说和你所有页面上的session_start()。

答案 1 :(得分:0)

您需要在索引文件中启动会话session_start(); $_SESSION['name'] = "test";

<强>的index.php

include 'index.php';

    echo "before destroying the session";
    print_r($_SESSION);
    unset($_SESSION['name']);//remove the name session variable which is available in my index page.
    session_destroy(); //destroy the session
    echo "after destroying the session";
    print_r($_SESSION);

<强> test.php的

before destroying the sessionArray ( [name] => test ) after destroying the sessionArray ( )

<强>输出

{{1}}