Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP Cookies

Cookies are small text files stored on the client's browser. PHP uses setcookie() to create them and $_COOKIE to read them. Cookies must be set before any HTML output.

Setting and Reading Cookies

The setcookie() function accepts: name, value, expiry, path, domain, secure, and httponly parameters.

Setting Cookies
<?php
// setcookie(name, value, expire, path, domain, secure, httponly)

// Simple cookie - expires in 1 hour
setcookie("username", "Alice", time() + 3600);

// Cookie with all parameters
setcookie(
    "theme",           // name
    "dark",            // value
    time() + 86400*30, // expire: 30 days
    "/",               // path: entire site
    "",                // domain: current domain
    true,              // secure: HTTPS only
    true               // httponly: no JS access
);

// Session cookie (expires when browser closes)
setcookie("temp_token", "abc123");

// Read cookies on next request
if (isset($_COOKIE["username"])) {
    echo "Welcome back, " . htmlspecialchars($_COOKIE["username"]);
} else {
    echo "No cookie found";
}
?>

Modifying and Deleting Cookies

To modify a cookie, call setcookie() again with the same name and a new value. To delete it, set the expiry to a time in the past.

Modify & Delete Cookies
<?php
// Modify - overwrite with new value and new expiry
setcookie("username", "Bob", time() + 3600);

// Delete - set expiry in the past
setcookie("username", "", time() - 3600);
// Also unset from current request's $_COOKIE
unset($_COOKIE["username"]);

// Check all cookies
foreach ($_COOKIE as $name => $value) {
    echo htmlspecialchars($name) . " = " . htmlspecialchars($value) . "\n";
}

// Practical: remember user preference
if (!isset($_COOKIE["lang"])) {
    setcookie("lang", "en", time() + 86400 * 365, "/");
}
$lang = $_COOKIE["lang"] ?? "en";
echo "Language: $lang";
?>
Key Takeaways
  • setcookie() must be called before any HTML output - it sends HTTP headers.
  • Cookies are accessible via the \ superglobal array.
  • Set the httponly flag to prevent JavaScript from accessing the cookie - protects against XSS.
  • Set the secure flag to ensure the cookie is only sent over HTTPS.
  • Use SameSite=Strict or SameSite=Lax to protect against CSRF attacks.
  • To delete a cookie, set its expiry time to the past: time() - 3600.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.