Destroy PHP session and unset all session variables
PHP Cookies and Sessions: Exercise-6 with Solution
Write a PHP script to destroy a session and unset all session variables.
Sample Solution:
PHP Code :
<?php
session_save_path('i:/custom/');
session_start();
// Unset all session variables
$_SESSION = [];
// Destroy the session
session_destroy();
echo "Session destroyed. All session variables have been unset.";
?>
Sample Output:
Session destroyed. All session variables have been unset.
Explanation:
In the above exercise -
- We start the session using session_start() to initialize the session.
- Use $_SESSION = [] to unset all session variables by assigning an empty array to $_SESSION. This effectively removes all session variables from the session.
- Then call session_destroy() to destroy the session. This deletes the session file on the server and removes the session ID from the client's browser.
- Finally, display a message indicating that the session has been destroyed and all session variables have been unset.
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Retrieve and display a PHP session variable.
Next: Set a secure PHP cookie for an encrypted connection.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/cookies-sessions/php-cookies-sessions-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics