PHP Cookies

PHP cookies are a way to store small pieces of data on the user's computer, which can persist across page loads and sessions. They’re often used for things like remembering login info, preferences, or tracking user behavior.

Setting a Cookie

Use setcookie() before any HTML output:

<?php // Set a cookie named "user" with value "John", expires in 1 hour setcookie("user", "John", time() + 3600, "/"); ?>

Parameters:

setcookie(name, value, expire, path, domain, secure, httponly);
  • name: Cookie name

  • value: Value to store

  • expire: Timestamp (e.g., time() + 3600 = 1 hour from now)

  • path: Scope of the cookie (default is current directory)

  • domain: Domain the cookie is available to

  • secure: Only send over HTTPS

  • httponly: Inaccessible via JavaScript (for security)


Accessing a Cookie

Cookies are available in the $_COOKIE superglobal:

<?php if (isset($_COOKIE["user"])) { echo "User is: " . $_COOKIE["user"]; } else { echo "Cookie not set"; } ?>

Deleting a Cookie

To delete a cookie, set its expiration time in the past:

<?php setcookie("user", "", time() - 3600, "/"); ?>