SyntaxStudy
Sign Up
PHP Intermediate 9 min read

Cookie Security

Cookies that contain sensitive data (session IDs, authentication tokens) must be protected against theft and tampering.

  • HttpOnly: prevents JavaScript access — mitigates XSS cookie theft.
  • Secure: only sent over HTTPS.
  • SameSite: controls when cookies are sent with cross-site requests — Strict or Lax mitigate CSRF.
  • Sign cookie values to detect tampering.
Example
<?php
// Signing cookies to prevent tampering
define('COOKIE_SECRET', 'your-secret-key-from-env');

function setCookieSigned(string $name, string $value, array $options = []): void
{
    $sig     = hash_hmac('sha256', $value, COOKIE_SECRET);
    $payload = base64_encode($value) . '.' . $sig;
    setcookie($name, $payload, array_merge([
        'path'     => '/',
        'httponly' => true,
        'secure'   => true,
        'samesite' => 'Lax',
    ], $options));
}

function getCookieSigned(string $name): ?string
{
    if (!isset($_COOKIE[$name])) return null;

    $parts = explode('.', $_COOKIE[$name], 2);
    if (count($parts) !== 2) return null;

    [$encodedValue, $sig] = $parts;
    $value = base64_decode($encodedValue);

    $expected = hash_hmac('sha256', $value, COOKIE_SECRET);
    if (!hash_equals($expected, $sig)) {
        // Tampered — reject
        return null;
    }
    return $value;
}

// Usage
setCookieSigned('user_pref', 'dark-mode', ['expires' => time() + 86400 * 30]);
$pref = getCookieSigned('user_pref'); // 'dark-mode' or null if tampered
Pro Tip

Tip: Never store sensitive data (passwords, PII, payment info) directly in cookies — even signed ones. Store a reference token, keep the actual data server-side, and validate the token on every request.