Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
<?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
Result
Open