Programming Languages PHP Subjective
Nov 23, 2012

How a cookie is destroyed?

Detailed Explanation

A cookie is destroyed by setting its expiration time to a past date.

Methods to Destroy Cookies:

// Method 1: Set expiration to past time
setcookie("username", "", time() - 3600); // 1 hour ago
setcookie("user_id", "", time() - 1); // 1 second ago

// Method 2: Set expiration to Unix epoch
setcookie("session_token", "", 1);

// Method 3: Using current time minus any value
setcookie("preferences", "", time() - 86400); // 24 hours ago

Complete Cookie Management:

// Create cookie with expiration
setcookie("user_data", "john_doe", [
    "expires" => time() + 3600, // 1 hour
    "path" => "/",
    "domain" => ".example.com",
    "secure" => true, // HTTPS only
    "httponly" => true, // No JavaScript access
    "samesite" => "Strict" // CSRF protection
]);

// Check if cookie exists
if (isset($_COOKIE["user_data"])) {
    echo "Cookie value: " . $_COOKIE["user_data"];
}

// Destroy specific cookie
function destroyCookie($name, $path = "/", $domain = "") {
    setcookie($name, "", [
        "expires" => time() - 3600,
        "path" => $path,
        "domain" => $domain
    ]);
    unset($_COOKIE[$name]);
}

// Destroy all cookies
foreach($_COOKIE as $name => $value) {
    destroyCookie($name);
}

Important: The path and domain must match the original cookie settings for successful deletion.

Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback