Is this a proper way to destroy all session data in php?

You should first know what sessions are: You can consider sessions as a data container on the server side that’s associated with a random identifier, the session ID. That session ID needs to be provided by the client so that the server can load the data associated to that session ID (and thus to that session) into the $_SESSION variable. Everything in that $_SESSION variable is also called session variables of the current active session.

Now to your questions:

Does the code will destroy all the sessions?? Is it the most common way? how do you guys destroy php sessions??

The provided code just deletes the session data of the current session. The $_SESSION = array(); statement will simply reset the session variable $_SESSION so that a future access on the session variable $_SESSION will fail. But the session container itself is not deleted yet. That will be done by calling session_destroy.

See also Truly destroying a PHP Session?

Oh yeah, btw, what is that session_name()?? All session name? e.g $_SESSION[‘var1’], $_SESSION[‘var2’]… ?

The session_name is just used to identify the session ID parameter passed in a cookie, the URL’s query or via a POST parameter. PHP’s default value is PHPSESSID. But you can change it to whatever you want to.

I dont need to use unset($_SESSION[‘var1’]); any more right???

No. The initial $_SESSION = array(); deletes all the session data.

Whats the different between using session_destroy and unset($_SESSION[])??

session_destroy will delete the whole session container while unset or resetting the $_SESSION variable will only delete the session data for the current runtime.

Leave a Comment