PHP 5.3 + How To Completely Destroy Session Variables In PHP

[contentblock id=300squaretextlink] [contentblock id=300squareimagelink]

The Sessions Bonanza

By default sessions are stored on the disk your server, you can find out the path by echo-ing for the attribute session.save_path:
echo ini_get( “session.save_path” );
(You can change that path in php.ini)

PHP Sessions are destroyed automatically when you close your browser. But what if you want to destroy the session before without closing the browser?

The Famous session_destroy – Remove Sessions From Disk


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.

What this means, is that session_destroy() will ONLY erase session data from the server’s disk! WHILE the data present
in the global $_SESSION is still present! So, session_destroy() is only the first part of the equation..

Clear Data Inside Globals – Remove session from $_SESSION

$_SESSION = array();

Now you would say that the global has been cleared and we have also remove sessions from the disk, so it’s done now? NO! Not yet..
Who is the culprit now?
HINT: Your browser!

Yes, your browser still retains / saves an essential ingredient of the session in the form of a cookie – more precisely the PHPSESSID.
This is like a Replicator from stargate (joking). Well, while the PHPSESSID helps your PHP-system to recreate the session back, it will not really contain all the previous data.
But still you really need to destroy this as well..

Final – Completely Destroy Session In PHP

Now that you know all the parts where session can have traces, the final code would now be like:

//remove PHPSESSID from browser
if ( isset( $_COOKIE[session_name()] ) )
setcookie( session_name(), “”, time()-3600, “/” );
//clear session from globals
$_SESSION = array();
//clear session from disk

To Summarize Destroying Sessions In PHP:

1- Remove Session data from the server’s disk
2- Remove data from globals
3- Clear any traces of PHPSESSID from your browser’s session cookie

4 Comment(s)

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.