Sessions, once created, needs to be destroyed when a user logs out or closes the application. By default a session automatically gets destroyed when a user closes her browser. This happens because of PHPSESSID cookie in user’s computer expires with quitting the browser. PHP Destroy Session is an essential step to make a reliable web application.
As a good web programming practice you must exclusively add the code to destroy a session. It will be beneficial in different situations. If your web application must automatically log out after a specific duration like in the case of Online Banking or some other financial transactions based application. This is to protect a user’s personal data if she forgets to logout.
Another case will be if a shopping website needs to clear shopping cart for a customer after a she places an order but still has not quitted the website. In short destroying session will be good to protect the personal, financial and confidential data of website users.
PHP Destroy Session –What Happens?
When a PHP session is destroyed the following things happen-
- All the data and variables used in the session are destroyed
- The global session variables and cookies associated with the session are not destroyed
Session_destroy() function
A session is destroyed by calling PHP Destroy Session function session_destroy(). This function does not require any parameters. It just erases the session data from storage by calling it in the PHP script as shown below.
session_destroy();
After a session is destroyed the $_SESSION superglobal array still contains the session data. The superglobal $_SESSION is cleared only when the script is terminated. Before the script is terminated or user closes the session, the S_SESSION superglobal data can be cleared by initializing it with an empty array.
$_SESSION=array();
session_destroy();
After doing all this to destroy a session, the PHPSESSID cookie may stay in a user’s system but without data. The next visit to the website by the user may re-start the session in her browser even if PHSESSID cookie is without any data. To avoid such situation the session must be completed deleted from the server and the browser by deleting the session cookie. This is explained in following example.
<?php session_start(); //call functions to do the tasks of your application //When all done and the session is to be destroyed $_SESSION = array(); //Destroy Session Cookie if (session_id() != "" || isset($_COOKIE[session_name()])) setcookie(session_name(), '', time() - 42000, '/'); // Now terminate the session session_destroy(); ?>
Unsetting the Session Variable
The session variables can be unset by using the unset() function and passing on the session variable. This will remove the session variable even if the session is not terminated.
unset($_SESSION[variable_name]);
Be First to Comment