?php
function destroy_session_and_data() {
session_start();
$_SESSION = array();
if (session_id() != "" || isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time() - 2592000, '/');
session_destroy();
} ?>
I understand the above code is used to terminate a session but I cant understand the need for the if condition and the setcookie command.
Also could you please explain what exactly is session_id() and session_name().
A clear explanation would be most appreciated. Thanks
PHP uses cookies to manage sessions; specifically, by setting an identifying key/value pair for that session inside a cookie.
PHPSESSID
. session_name()
returns the session name or, if a parameter is passed, updates the session name.session_id()
returns the session id or, if a parameter is passed, updates the session id.The code in the question checks if there is session passed with the request: first by starting/reactivating the session with session_start()
, then checking for an existing cookie matching the session name. If the code finds one, it forces the browser to remove the cookie by setting its expiration date to a time in the past.
From the manual:
session_id()
is used to get or set the session id for the current session.
session_name()
returns the name of the current session. If name is given, session_name()
will update the session name and return the old session name.
The id
is used as a primary key (unique) for the database in which the sessions are stored (by default just in files ondisk), the name
is just a name. I'm not sure if name
needs to be unique.
So in this case, the code is checking if either the session_id (get data from browser cookie and lookup in local db) or if there is a cookie with given session_name. If so, it sets the expiry time of the cookie (client side) to 43,2 minutes ago and destroys the session (server side).
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