Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is session_id( ) and session_name( )? Explain how they are being used in the following code

?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

like image 815
Sahil Avatar asked Dec 19 '12 12:12

Sahil


2 Answers

PHP uses cookies to manage sessions; specifically, by setting an identifying key/value pair for that session inside a cookie.

  • The name of the session is the name of the cookie; the default name for PHP-based websites is PHPSESSID. session_name() returns the session name or, if a parameter is passed, updates the session name.
  • The key/value pair inside the cookie describes the session id; the key denotes that it is the session identifier, and the value is the session identifier itself. 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.

like image 108
Maxim Krizhanovsky Avatar answered Nov 09 '22 05:11

Maxim Krizhanovsky


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).

like image 1
wkoot Avatar answered Nov 09 '22 05:11

wkoot