agyanadda@gmail.com

PHP Cookies

PHP Forms and Web 1 min read Updated Dec 1, 2026 Topic 26 of 36

A cookie is a small piece of data stored in the browser and sent back to the server with every request.

Create a cookie

setcookie('theme', 'dark', [
    'expires' => time() + 60 * 60 * 24 * 30, // 30 days
    'path' => '/',
    'secure' => true,     // HTTPS only
    'httponly' => true,   // JavaScript cannot read it
    'samesite' => 'Lax',
]);

setcookie() must run before any output.

Read

$theme = $_COOKIE['theme'] ?? 'light';

A new cookie appears in $_COOKIE only on the next request.

Delete

Set the expiry in the past: setcookie('theme', '', time() - 3600, '/');

Good uses

Remember language, theme, "remember me" tokens, recently viewed items.

Do not store

Passwords or anything secret — users can see and edit cookies. Size limit is about 4 KB per cookie.

In India and the EU, tell users about non-essential cookies (consent banner).

Example

Example — Remember the visitor's language PHP
<?php
$allowed = ['en' => 'English', 'hi' => 'हिन्दी'];

if (isset($_GET['lang']) && isset($allowed[$_GET['lang']])) {
    setcookie('lang', $_GET['lang'], [
        'expires' => time() + 60 * 60 * 24 * 365,
        'path' => '/',
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    $_COOKIE['lang'] = $_GET['lang']; // use it on this request too
}

if (isset($_GET['forget'])) {
    setcookie('lang', '', time() - 3600, '/');
    unset($_COOKIE['lang']);
}

$lang = $_COOKIE['lang'] ?? 'en';
$greeting = $lang === 'hi' ? 'नमस्ते! आपका स्वागत है।' : 'Hello! Welcome.';
?>
<h3><?= $greeting ?></h3>
<p>Language: <?= $allowed[$lang] ?></p>
<a href="?lang=en">English</a> | <a href="?lang=hi">हिन्दी</a> | <a href="?forget=1">Forget</a>

Choose a language, close and reopen the page — the cookie remembers your choice for a year.

Test Yourself With Exercises

Exercise 1 Multiple Choice

How do you delete a cookie?

Exercise 2 True / False

httponly cookies cannot be read by JavaScript.

Exercise 3 Fill in the Blank

Cookies are created with the ___() function.

Frequently Asked Questions

The browser sends the cookie back only on the next request. Reload the page, or also set $_COOKIE manually for the current request.