0
0
PHPprogramming~5 mins

Destroying sessions in PHP

Choose your learning style9 modes available
Introduction

Destroying sessions helps you log users out safely and clear their data from the server.

When a user clicks the logout button on a website.
When you want to clear all saved user data after a session ends.
To protect user privacy by removing session information.
When you want to reset the session to start fresh.
To prevent unauthorized access after a user leaves the site.
Syntax
PHP
<?php
session_start();
// Destroy all session data
session_unset();
session_destroy();
?>

session_start() must be called before destroying the session.

session_unset() clears all session variables.

Examples
This code starts the session, clears all session variables, and then destroys the session.
PHP
<?php
session_start();
session_unset();
session_destroy();
?>
Another way to clear session variables by setting the session array to empty before destroying.
PHP
<?php
session_start();
$_SESSION = array();
session_destroy();
?>
Sample Program

This program sets a session variable, shows it, then destroys the session and shows that the data is gone.

PHP
<?php
// Start the session
session_start();

// Set a session variable
$_SESSION['username'] = 'Alice';

// Show session data before destroying
echo "Before destroying: " . ($_SESSION['username'] ?? 'No user') . "\n";

// Clear session variables
session_unset();

// Destroy the session
session_destroy();

// Try to access session data after destroying
echo "After destroying: " . ($_SESSION['username'] ?? 'No user') . "\n";
?>
OutputSuccess
Important Notes

Always call session_start() before working with sessions.

Destroying a session does not delete the session cookie on the browser automatically.

To fully log out a user, consider deleting the session cookie as well.

Summary

Destroying sessions clears user data and ends the session safely.

Use session_unset() to clear variables and session_destroy() to end the session.

Always start the session with session_start() before destroying it.