Skip to content
← Back to Snippets
Code

Delete a Cookie

Deletes a cookie by queuing an expired Set-Cookie header with matching path and safety options.

Purpose

Deletes a cookie by queuing an expired Set-Cookie header with matching path and safety options.

Snippet details

ContextCookieLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Security

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.
 */

/**
 * Delete a Cookie.
 *
 * Purpose:
 * Queues an expired cookie header so the browser removes the cookie.
 *
 * @param string $name Cookie name.
 * @return array Cookie deletion result.
 */
function ogSnippetDeleteACookie(string $name): array {
	$result = array(
		'ok' => false,
		'message' => 'Cookie delete header was not queued.'
	);

	$name = trim($name);

	if ($name === '' || headers_sent() === true) {
		return $result;
	}

	$options = array(
		'expires' => time() - 3600,
		'path' => '/',
		'secure' => true,
		'httponly' => true,
		'samesite' => 'Lax'
	);

	if (setcookie($name, '', $options) === true) {
		$result['ok'] = true;
		$result['message'] = 'Cookie delete header was queued.';
	}

	return $result;
}

$delete_result = ogSnippetDeleteACookie('og_stargate_visit');

echo 'Delete cookie result: '.$delete_result['message'];