← Back to Chapters

PHP $_COOKIE Variable

? PHP $_COOKIE Variable

? Quick Overview

The $_COOKIE superglobal in PHP is used to retrieve data stored in cookies. Cookies allow small pieces of data to persist in the user's browser across multiple page loads.

? Key Concepts

  • Cookies are stored on the client browser
  • Data persists between page requests
  • Accessed using $_COOKIE

⚙️ Syntax / Theory

The setcookie() function is used to create cookies.

? View Code Example
// Syntax for setting a cookie in PHP
setcookie(name, value, expire, path, domain, secure, httponly);

? Setting a Cookie

This example sets a cookie named user that expires in one hour.

? View Code Example
// Set a cookie that expires after one hour
<?php
setcookie("user", "JohnDoe", time() + 3600, "/");
echo "Cookie has been set!";
?>

? Accessing Cookie Data

? View Code Example
// Check and read cookie value
<?php
if(isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"];
} else {
echo "Cookie not set.";
}
?>

? Output / Explanation

If the cookie exists, its value is displayed. Otherwise, a fallback message is shown.

?️ Deleting a Cookie

? View Code Example
// Delete a cookie by setting expiration in the past
<?php
setcookie("user", "", time() - 3600, "/");
echo "Cookie has been deleted!";
?>

? Interactive Example

Cookies are commonly used to remember theme preferences, login state, or language selection across page reloads.

? Use Cases

  • User login persistence
  • Theme or language preference storage
  • Tracking visits or sessions

✅ Tips & Best Practices

  • Always call setcookie() before any output
  • Use httponly and secure flags for security
  • Sanitize cookie values before usage

? Try It Yourself

  • Store a light/dark theme preference in a cookie
  • Create a logout button that deletes cookies
  • Experiment with different expiration times