PHP has no deleteCookie() function. To remove a cookie, you set it again with an expiry in the past. The browser sees that it has expired and deletes it.
<?php
setcookie("theme", "", [
"expires" => time() - 3600,
"path" => "/",
]);
The attributes must match
A cookie is identified by its name, path and domain together. To delete it, send the same path (and domain) that you used when you created it.
<?php
// created with:
setcookie("theme", "dark", ["expires" => time() + 3600, "path" => "/shop"]);
// this does NOT delete it, because the path differs:
setcookie("theme", "", ["expires" => time() - 3600, "path" => "/"]);
// this does:
setcookie("theme", "", ["expires" => time() - 3600, "path" => "/shop"]);
If a cookie “will not delete”, compare the path and domain in the developer tools first.
Also remove it in this request
Deleting sends a header. $_COOKIE still holds the old value for the rest of this script. Remove it from the array too, if you read it again later.
<?php
$_COOKIE = ["theme" => "dark", "lang" => "en"];
unset($_COOKIE["theme"]);
print_r($_COOKIE);
Array
(
[lang] => en
)
A helper
<?php
function deleteCookie(string $name, string $path = "/"): void
{
setcookie($name, "", [
"expires" => time() - 3600,
"path" => $path,
"secure" => true,
"httponly" => true,
"samesite" => "Lax",
]);
unset($_COOKIE[$name]);
}
Delete all your cookies
<?php
foreach (array_keys($_COOKIE) as $name) {
deleteCookie($name);
}
The session cookie is deleted in the way shown in Destroying a Session.
Clear a cookie from the browser side
Visitors can delete cookies in their browser settings at any time. Your code must never depend on a cookie still being there.