Home » Php » php – What exactly is session_id( ) and session_name( )? Explain how they are being used in the following code

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

Posted by: admin July 12, 2020 Leave a comment

Questions:
?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

How to&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.

Answer:

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

Answer:

to know what “session” a visitor is in, a cookie is set. As long as that cookie is available, the user will remain in the same session. To end the session, it needs to be removed (that explains the setcookie().

session_id() and session_name() are in the php manaul