2016-05-23 156 views
0

我正在用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 () 

为什么我会是可用在指数页面无法在上面的脚本页面中访问?

在此先感谢

+0

你写这里面的session_start()。它为我工作很好。 – RJParikh

+0

是的,它在第一行。 – scriptkiddie

+0

如果您将索引页面包含在另一个页面中并且您的索引页面包含会话开始,则不需要再次使用session_start()。 – RJParikh

回答

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()。

0

您需要在索引文件中启动会话session_start()

的index.php

session_start(); 
$_SESSION['name'] = "test"; 

test.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); 

输出

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

上面试试代码来实现你的愿望输出。 @scriptkiddie – RJParikh