doukuipei9938 2014-02-08 11:22
浏览 92
已采纳

Session_start不起作用或Session_destroy不起作用?

I have this code in a default index page:

<?php 
$_SESSION['user'] = 'Bill';
print $_SESSION['user'];

$_SESSION = array();
session_destroy();

$_SESSION['user'] = 'Andy';
print $_SESSION['user'];
?>

The output is the following:

Bill
Warning: session_destroy(): Trying to destroy uninitialized session in C:\xampp\htdocs\DSP\index.php on line 15
Andy

Obviously I have to initialize the session with session_start() but these are my questions:

1) However, why can I store a session without session_start() function?

2) Now I put session_start() function on the top of the code:

<?php 
session_start();

$_SESSION['user'] = 'Bill';
print $_SESSION['user'];

$_SESSION = array();
session_destroy();

$_SESSION['user'] = 'Andy';
print $_SESSION['user'];
?>

Now the output is the following:

Bill
Andy

My question now is:

3) Why Andy is printed on the output? Why compiler NOT gives me error that session must be started again beacuse I destroyed it before with the command session_destroy()?

Thanks everyone very much!

  • 写回答

2条回答 默认 最新

  • duangai9678 2014-02-08 11:36
    关注

    However, why can I store a session without session_start() function?

    Because it's just a usual array and can be accessed as such. It is same with $_POST, $_GET and other super-global arrays. However, the session is only created after you call session_start(), so trying to store information in the array before initializing the session is pointless.

    I don't see anything unusual in your code and the output produced. To illustrate, see the following code:

    <?php 
    session_start();
    
    $_SESSION['user'] = 'Bill';    
    var_dump($_SESSION);
    
    $_SESSION = array();
    session_destroy();    
    var_dump($_SESSION);
    
    $_SESSION['user'] = 'Andy';
    var_dump($_SESSION);
    

    The output is:

    array(1) {
      ["user"]=>
      string(4) "Bill"
    }
    
    array(0) {
    }
    
    array(1) {
      ["user"]=>
      string(4) "Andy"
    }
    

    This is what happens above:

    • Session is initialized using session_start()
    • A string Bill with the key user is added to the associative array
    • session_destroy() destroys the session data that is stored in the session storage. ($_SESSION is now empty)
    • Another string Andy with the key user is added to the associative array

    As you'd expect, the output would be Andy. I don't see the issue?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数