SyntaxStudy
Sign Up
PHP Beginner 6 min read

Cookie Basics

Cookies are small pieces of data stored in the browser and sent back to the server with every request to the same domain. PHP reads incoming cookies via $_COOKIE and writes them with setcookie().

  • Cookies set with setcookie() are available in $_COOKIE only on the next request.
  • Always pass the full options array (PHP 7.3+) rather than positional arguments.
  • To delete a cookie, set its expiry to a time in the past.
Example
<?php
// Set a cookie (must be called before any output)
setcookie('theme', 'dark', [
    'expires'  => time() + (86400 * 30), // 30 days
    'path'     => '/',
    'domain'   => 'example.com',
    'secure'   => true,  // HTTPS only
    'httponly' => true,  // not accessible via JS
    'samesite' => 'Lax',
]);

// Read a cookie on subsequent requests
$theme = $_COOKIE['theme'] ?? 'light';
echo "Current theme: $theme";

// Update a cookie — just call setcookie() again with the same name
setcookie('theme', 'light', [
    'expires'  => time() + (86400 * 30),
    'path'     => '/',
    'httponly' => true,
    'samesite' => 'Lax',
]);

// Delete a cookie — set expiry in the past
setcookie('theme', '', [
    'expires'  => time() - 3600,
    'path'     => '/',
]);

// Check if a cookie exists
if (isset($_COOKIE['theme'])) {
    echo "Theme preference found: " . htmlspecialchars($_COOKIE['theme']);
}
Pro Tip

Tip: Prefer the array-based setcookie() syntax (PHP 7.3+). It is far less error-prone than the old positional argument form, especially for the samesite attribute which cannot be set positionally in older PHP versions.