1
session_start();
$_SESSION['name'] = 'Sam';
echo $_SESSION['name'];//Sam
session_destroy();
echo $_SESSION['name'];//Sam

I know that using unset() or $_SESSION = array() can unset $_SESSION value But I am still wondering why session_destroy() cannot unset the $_SESSION value, what exactly did session_destroy() do?

When is it appropriate to use session_destroy()?

Do I need to call session_destroy() after using unset()?

Wei-Jie Yu
  • 73
  • 1
  • 6

1 Answers1

1

The manual entry for session_destroy says:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

So, session_destroy() will destroy the data where it's actually stored (filesystem/memcached/Redis/whatever, depending on the session handler that has been configured), but the same data will still stay in memory in the $_SESSION superglobal, until you explicitly unset it, either with unset() or $_SESSION = [].

So, yes, you have to call session_destroy() after using unset(), as the example on the manual page for session_destroy() says: https://www.php.net/manual/en/function.session-destroy.php#refsect1-function.session-destroy-examples

And finally, to answer your primary question "Why session_destroy cannot unset the current session value php": because that's not what this function is for. The manual says it all. Just read it carefully and you'll know everything about session cleaning.

Bartosz Zasada
  • 3,762
  • 2
  • 19
  • 25