What does session_destroy()
function do? To delete all session variables in global array $_SESSION I have to use session_unset()
. To remove session from the client browser (delete session id and name) I have to unset cookies:
unset($_COOKIES[session_id()]);
unset($_COOKIES[session_name()]);
Why session_destroy()
function is needed?
session_destroy() will delete the session file (if file storage is used). Otherwise the session file will reside on the server until the garbage collection deletes it. So, if you want to make sure that the stored session data is removed from the server you have to call session_destroy(). Do not call this on every page!
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. To use the session variables again, session_start() has to be called.
A PHP session can be destroyed by session_destroy() function.
session_destroy() will destroy all the sessions, while the above line would destroy a specific session variable.
session_destroy()
ends the whole session, meaning it will be removed from PHP's session storage and can't ever be used again. If you'd only unset the session variables and cookies, the session would still be active server-side and could potentially be recycled if some session variables are set again and the cookie with the original session ID is sent to the client again.
To put it in another way: a session basically consists of a secret ID stored somewhere on the web server, together with session variables registered to that session. The session ID is sent to the client (usually as a cookie) so the client can be identified as 'owner' of the session on later requests. Assuming a session has already been created and has variables registered to it, here's an overview of what the functions do:
session_start()
imports all session variables belonging to the session ID that the client sent from the session registry to the $_SESSION
arraysession_unset()
or calling unset()
on $_SESSION
variables will clear all variables registered to the current session, but it will not clear the session itselfsession_destroy()
is the only function that will actually purge the session from the session registry, thus literally 'destroying' the sessionWhile session_destroy()
will unregister all session variables, it won't clear the $_SESSION
array in the script that's currently executing, so it's still a good idea to unset the session variables to prevent bugs and security issues.
On a related note, the PHP manual recommends not to use session_unset()
but rather unset the keys from $_SESSION
:
If
$_SESSION
(or$HTTP_SESSION_VARS
for PHP 4.0.6 or less) is used, useunset()
to unregister a session variable, i.e.unset($_SESSION['varname']);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With