w3resource

Destroy PHP session and unset all session variables


6. Destroy Session and Unset Variables

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:

Flowchart: Destroy PHP session and unset all session variables.

For more Practice: Solve these Related Problems:

  • Write a PHP script to destroy the current session and confirm that all session variables have been removed.
  • Write a PHP function to unset all session variables and then redirect the user to a login page.
  • Write a PHP program to safely end a session and output a message confirming session termination.
  • Write a PHP script to clear session data and then check using session_status() to ensure the session is inactive.

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.



Follow us on Facebook and Twitter for latest update.