</>
Skip to content
PHP lessons (29/49)

PHP — Cookies

Setting cookies

<?php
// Set cookie (must be before any output)
setcookie('username', 'Alice', time() + 3600, '/');
setcookie('theme', 'dark', time() + 86400, '/', '.example.com', true, true);

// Set with parameters
setcookie(
    'user_prefs',
    json_encode(['lang' => 'en', 'theme' => 'dark']),
    time() + 30 * 24 * 60 * 60, // 30 days
    '/',
    '',
    false,
    true
);
?>

Reading cookies

<?php
if (isset($_COOKIE['username'])) {
    echo "Welcome, " . $_COOKIE['username'];
}

// Parse JSON cookie
if (isset($_COOKIE['user_prefs'])) {
    $prefs = json_decode($_COOKIE['user_prefs'], true);
    echo "Language: " . $prefs['lang'];
}
?>

Deleting cookies

<?php
// Set expiration in the past
setcookie('username', '', time() - 3600, '/');
unset($_COOKIE['username']);
?>

Cookie security

<?php
setcookie('token', $value, [
    'expires' => time() + 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,    // HTTPS only
    'httponly' => true,  // No JavaScript access
    'samesite' => 'Strict'
]);
?>

Sessions vs cookies

FeatureSessionsCookies
StorageServerBrowser
SizeUnlimited4KB
SecurityMore secureLess secure
LifetimeUntil browser closesConfigurable
Use caseLogin statePreferences

Mini Practice

Write PHP code that:

  1. Sets a cookie with expiration
  2. Reads a cookie value
  3. Deletes a cookie
  4. Compares sessions and cookies

Up Next

In the next lesson, you'll learn about Forms — processing HTML forms.

Related Topics

Frequently Asked Questions about Cookies

What is Cookies in PHP?

Cookies is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Cookies?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Cookies.

Why is Cookies important in PHP?

Cookies is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.