Destroy a Session in PHP
To destroy a session in PHP, you can use the session_destroy()
function. This function will unset all session variables, effectively ending the session. Here's an example:
<?php
// Start the session
session_start();
// Unset all session variables
$_SESSION = array();
// Destroy the session
session_destroy();
// Redirect or display a message as needed
header("Location: login.php"); // Redirect to login page after destroying the session
exit();
?>
In this example:
session_start()
initializes or resumes the session.$_SESSION = array();
unsets all session variables by assigning an empty array to $_SESSION
.session_destroy()
destroys the session. Note that this function only destroys the session data on the server; it doesn't unset the session variables or remove the session cookie from the client.Remember to call session_start()
on every page where you want to work with session variables. The example above assumes that the user is redirected to a login page after logging out; adjust the redirection URL according to your application's structure.
If you want to unset specific session variables without destroying the entire session, you can use the unset()
function. For example:
<?php
// Start the session
session_start();
// Unset specific session variables
unset($_SESSION['user_id']);
unset($_SESSION['username']);
// Rest of your PHP code
?>
This removes the specified session variables without ending the entire session.
Thank you.