How to Destroy a Session and All Data in PHP

This article explains how to completely and securely destroy a PHP session and clear all associated session data. You will learn the essential three-step process required to clear the session superglobal, delete the session cookie from the client’s browser, and terminate the session file on the server.

Simply calling session_destroy() is not enough to secure a user’s logout, as it does not immediately empty the $_SESSION superglobal array or delete the session cookie stored in the user’s browser. To properly destroy a session and all its data, you must perform the following steps in order.

The Complete PHP Session Destruction Script

Below is the standard, secure code block used to completely tear down a PHP session:

// Step 1: Start the session to access it
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Step 2: Unset all session variables
$_SESSION = array();

// Step 3: Delete the session cookie from the browser
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(), 
        '', 
        time() - 42000,
        $params["path"], 
        $params["domain"],
        $params["secure"], 
        $params["httponly"]
    );
}

// Step 4: Destroy the session on the server
session_destroy();

How Each Step Works

  1. Start the Session: You cannot destroy a session unless PHP knows which session to target. If a session is not already active, you must initialize it using session_start().
  2. Clear the Superglobal Array: Setting $_SESSION = array() empties the active session array in the current script execution. This prevents any subsequent code in the current request from reading the old session data.
  3. Delete the Session Cookie: Sessions rely on a cookie stored in the user’s browser (usually named PHPSESSID) to identify the user. To delete this cookie, you must expire it by using setcookie() with a timestamp in the past (time() - 42000). Using session_get_cookie_params() ensures that the cookie is cleared with the exact same path, domain, and security settings with which it was created.
  4. Destroy the Server Data: Calling session_destroy() deletes the physical session file stored on the web server’s file system, officially ending the session.