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 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多