What are session_id () and session_name ()? Explain how they are 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 that the above code is used to end the session, but I cannot understand the need for the if condition and the setcookie command.

Also could you please explain what exactly session_id () and session_name () are.

A clear explanation will be appreciated. Thanks

+7
source share
3 answers

PHP uses cookies to manage sessions; in particular, by setting an identifier key / value pair for this session inside the cookie.

  • Session Name is the name of the cookie; The default name for PHP-based websites is PHPSESSID . session_name() returns the name of the session or, if the parameter is passed, updates the name of the session.
  • The key / value pair inside the cookie describes the session identifier; the key means that this is a session identifier, and the value is the session identifier itself. session_id() returns the session identifier or, if the parameter is passed, updates the session identifier.

The code in the question checks whether the session with the request has passed: first starting / reactivating the session using session_start() , then checking for the existence of an existing cookie corresponding to the session name. If the code finds it, it forces the browser to delete the cookie, setting the expiration date in the past.

+3
source

From the manual:

session_id() used to get or set the session identifier for the current session.

session_name() returns the name of the current session. If a name is specified, session_name() update the session name and return the name of the old session.

id used as the primary key (unique) for the database in which the sessions are stored (by default only in ondisk files), name is just a name. I am not sure that name should be unique. Thus, in this case, the code checks if session_id is (getting data from the browser cookie and searching in the local db) or if there is a cookie with the given name session_name. If so, it sets the cookie expiration time (client side) to 43.2 minutes ago and destroys the session (server side).

+1
source

a cookie is set to find out what a visitor’s session is. As long as this cookie is available, the user will remain in the same session. To end a session, you need to delete it (this explains setcookie ().

session_id () and session_name () are in php manaul

0
source

All Articles