session_destroy() , session_unset() , session_abort()

session_unset() unsets all session variables ($_SESSION[])

example 1:

[code language=”php”]
session_start();
$_SESSION[‘name’]=”Mehdi”;
echo $_SESSION[‘name’];
session_unset();
echo $_SESSION[‘name’];
[/code]

Output: 
Mehdi
Notice: Undefined index: name on line 4

So the session variables are gone immediately but the session file is still there (So is the cookie(PHPSESSID) which is having sessionID. )


session_destroy() destroys session data in storage

pay attention to this example :

Page X.php :

[code language=”php”]
session_start();
$_SESSION[‘name’]=”Mehdi”;
echo $_SESSION[‘name’];
session_unset();
echo $_SESSION[‘name’];
echo “another page “;
[/code]

Output:
Mehdi Mehdi another page

Page  Y.php :

[code language=”php”]
session_start();
echo $_SESSION[‘name’];
[/code]

And when you proceed to page Y :

Notice: Undefined index: name on line 2

so session_Destroy() destroys session data in storage , if you are in the page x and you call session_destroy() there , after calling it , you still can access to the variable $_SESSION[”] but if you lead to another page that session is gone . But ! even if you start a new session in the second page (Y) , it won’t generate a new session id and uses the previous one from the cookie stored previously unless you have also deleted the cookie PHPSESSID .

we delete the PHPSESSID cookie like this :

[code language=”php”]
setcookie(“PHPSESSID”,null,-1,”/”);
[/code]


session_abort()  closes the current session and discards the changes applied to Session array in the current page  , it doesn’t delete the session file

page 1.php :

[code language=”php”]
session_start();
$_SESSION[‘city’]=”Sydney”;
echo “ page2“;
[/code]

when you open this page , a session file is created on the server (to find out where session files are saved run “echo session_save_path()” )  with the name of session_id  and the content of  the variable :

  sess_o22iabs75j93uhc7i4jf1lecjk  (file name)
  city|s:6:"Sydney";               (content)

if we go to 2.php containing this code :

[code language=”php”]
session_start();
$_SESSION[‘country’]=”Australia”;
echo session_encode();
session_abort();
session_start();
echo session_encode();
[/code]

when session_abort is executed , the session is closed and the change which here is the ‘country’ element of Session array is discarded .

Output : 
city|s:6:"Sydney";country|s:9:"Australia";
city|s:6:"Sydney";

PS : This is my first post here . i hope i could keep posting till one day it pays off :)) and please leave some comments below . that means a lot to me.

4 thoughts on “session_destroy() , session_unset() , session_abort()

Leave a Reply

Your email address will not be published. Required fields are marked *