Php – Difference between unset($_SESSION[]), session_unset() and session_destroy() in PHP

PHPsession

I need help regarding session in php

I tried this code

<?php 
session_start();
$_SESSION['one'] = "Hello";
$_SESSION['two'] = "World";
$_SESSION['three'] = "Welcome to session";
var_dump($_SESSION);

It prints

array (size=3)
  'one' => string 'Hello' (length=5)
  'two' => string 'World' (length=5)
  'three' => string 'Welcome to session' (length=18)

Then I unset the session one

unset($_SESSION['one']);
echo "Session one unset and only session two and three exist";
var_dump($_SESSION);

And it prints

Session one unset and only session two and three exist
array (size=2)
  'two' => string 'World' (length=5)
  'three' => string 'Welcome to session' (length=18)

Then if I destroy the session

session_destroy();
echo "Session Destroyed <br />";
var_dump($_SESSION);

But nothing happens and I can still print the session as

Session Destroyed 
array (size=2)
  'two' => string 'World' (length=5)
  'three' => string 'Welcome to session' (length=18)

But if i use session_destroy(); again it gives me a warning

Warning: session_destroy(): Trying to destroy uninitialized session

And instead of session_destroy() code if i use unset

session_unset('two');
echo "Session two unset";
var_dump($_SESSION);

All the session variables get unset and i cant access the session three variable
It prints

Session two unset
array (size=0)
  empty

Instead of using session_unset('two'); if I use session_unset(); then I also it gives me the same result.

So what is the actual difference between unset($_SESSION['one']), session_unset('one'), session_unset() and session_destroy().

I googled it and everywhere I got the answer that session_destroy() is used to destroy the whole session (but in the code above I can still access the session variable) and session_unset('one') is used to unset only a single session variabele (But in the code above if I use session_unset('one') all the session variables get unset).

So Please help me understand how session works, Also what code should be used while logging our users, session_unset() or session_destroy().

Best Answer

Its pretty simple,

session_unset — Free all session variables, but session id will not be destroy

session_destroy — Destroys all data registered to a session, to call this function first session should be registered.

unset($_SESSION['VARIABLE_NAME']) - This will unset variable value which you passed.

In your example, calling session_destroy() directly is not correct, as a result you can see the values of variable which are there in session, you can call session_destroy for registered session.

Thanks Amit