Skip to content
← Back to Snippets
Code

Destroy a Session

Destroys the active PHP session, clears the session array, and expires the session cookie for logout or reset workflows.

Purpose

Destroys the active PHP session, clears the session array, and expires the session cookie for logout or reset workflows.

Snippet details

ContextSessionLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Sessions and Authentication

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Destroy a Session.
 *
 * Purpose:
 * Clears server-side session data and asks the browser to expire the session
 * cookie when a user logs out or a session must be reset.
 *
 * @return array Logout cleanup status.
 */
function ogSnippetDestroyASession(): array {
	if (session_status() !== PHP_SESSION_ACTIVE) {
		if (headers_sent() === true) {
			return array(
				'ok' => false,
				'status' => 'session-not-active-and-headers-sent'
			);
		}

		session_start();
	}

	$_SESSION = array();

	if (ini_get('session.use_cookies')) {
		$cookie_params = session_get_cookie_params();

		setcookie(
			session_name(),
			'',
			time() - 42000,
			$cookie_params['path'],
			$cookie_params['domain'],
			$cookie_params['secure'],
			$cookie_params['httponly']
		);
	}

	$destroyed = session_destroy();
	$status_message = 'destroy-failed';

	if ($destroyed === true) {
		$status_message = 'destroyed';
	}

	return array(
		'ok' => $destroyed,
		'status' => $status_message
	);
}

// Logout controller usage before rendering output:
// $logout_report = ogSnippetDestroyASession();
// header('Location: /');
// exit;