简体   繁体   中英

Session_start doesn't work or Session_destroy doesn't work?

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!

You should unset the session before trying to destroy it.

session_unset();
session_destroy();

http://www.php.net/manual/en/function.session-unset.php

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM