Session 4.1 – PHP Cookies

Module 4: PHP Filters and Handlers | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Understand what cookies are and how they work in web applications
  • Create and set cookies using PHP's setcookie() function
  • Retrieve and access cookie values
  • Modify existing cookies and delete cookies when needed
  • Implement secure cookie practices including HttpOnly and Secure flags
  • Build practical applications using cookies for user preferences and tracking

Introduction to PHP Cookies

Cookies are small pieces of data stored on the client's browser that allow web applications to remember information about users across multiple page requests and visits. They are essential for maintaining state in the stateless HTTP protocol.

Key Insight

Cookies enable web applications to remember user preferences, maintain login sessions, track user behavior, and provide personalized experiences without requiring users to re-enter information on every page visit.

What Are Cookies?

A cookie is a small text file that a web server stores on a client's computer. Cookies typically contain:

Name

A unique identifier for the cookie

Value

The data stored in the cookie

Expiration

When the cookie should be deleted

Path

The URL path where the cookie is valid

Domain

The domain for which the cookie is valid

Security Flags

Secure and HttpOnly attributes

Creating Cookies in PHP

PHP provides the setcookie() function to create cookies. The function must be called before any output is sent to the browser.

Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Basic Cookie Example:
<?php
// Create a cookie that expires in 30 days
$cookie_name = "username";
$cookie_value = "JohnDoe";
$expire_time = time() + (30 * 24 * 60 * 60); // 30 days

setcookie($cookie_name, $cookie_value, $expire_time, "/");

echo "Cookie '" . $cookie_name . "' has been set!";
?>
Important Note

The setcookie() function must be called before any HTML output, including whitespace, blank lines, or even before the <!DOCTYPE> declaration. Otherwise, you'll receive a "headers already sent" error.

Cookie with All Parameters:
<?php
$cookie_name = "user_preference";
$cookie_value = "dark_mode";
$expire = time() + (86400 * 30); // 30 days
$path = "/";
$domain = ""; // Current domain
$secure = true; // Only transmit over HTTPS
$httponly = true; // Not accessible via JavaScript

setcookie($cookie_name, $cookie_value, $expire, $path, $domain, $secure, $httponly);
?>

Retrieving Cookie Values

PHP automatically makes cookies available through the $_COOKIE superglobal array. You can access cookie values using the cookie name as the array key.

Checking and Retrieving Cookies:
<?php
// Check if a cookie exists
if(isset($_COOKIE["username"])) {
    echo "Welcome back, " . $_COOKIE["username"] . "!";
} else {
    echo "Welcome, Guest! Please log in.";
}
?>
Safely Retrieving Cookie Values:
<?php
// Using htmlspecialchars to prevent XSS attacks
if(isset($_COOKIE["username"])) {
    $username = htmlspecialchars($_COOKIE["username"]);
    echo "Hello, " . $username;
}

// Using default values
$theme = isset($_COOKIE["theme"]) ? $_COOKIE["theme"] : "light";
echo "Current theme: " . $theme;
?>
Displaying All Cookies:
<?php
if(count($_COOKIE) > 0) {
    echo "Current Cookies:<br>";
    foreach($_COOKIE as $name => $value) {
        echo $name . " = " . $value . "<br>";
    }
} else {
    echo "No cookies found.";
}
?>

Modifying Existing Cookies

To modify a cookie, simply set it again with the same name but with different parameters. The new cookie will overwrite the old one.

<?php
// Original cookie
setcookie("username", "JohnDoe", time() + 3600, "/");

// Modify the cookie (update value)
setcookie("username", "JaneSmith", time() + 3600, "/");

// Extend expiration time
setcookie("username", "JohnDoe", time() + (86400 * 60), "/"); // 60 days
?>
Note

When modifying a cookie, ensure that the path and domain parameters match the original cookie, or the browser will treat it as a different cookie.

Deleting Cookies

To delete a cookie, set its expiration time to a past date. This tells the browser to remove the cookie.

Deleting a Cookie:
<?php
// Delete a cookie by setting expiration to past
setcookie("username", "", time() - 3600, "/");

// Alternative method
setcookie("username", "", 1, "/");

echo "Cookie has been deleted.";
?>
Deleting Multiple Cookies:
<?php
// Delete all cookies
if(count($_COOKIE) > 0) {
    foreach($_COOKIE as $name => $value) {
        setcookie($name, "", time() - 3600, "/");
    }
    echo "All cookies have been deleted.";
}
?>
Complete Cookie Management Example:
<?php
function createCookie($name, $value, $days = 30) {
    $expire = time() + ($days * 24 * 60 * 60);
    setcookie($name, $value, $expire, "/");
}

function getCookie($name, $default = null) {
    return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $default;
}

function deleteCookie($name) {
    if(isset($_COOKIE[$name])) {
        setcookie($name, "", time() - 3600, "/");
        unset($_COOKIE[$name]);
        return true;
    }
    return false;
}

// Usage
createCookie("user_id", "12345", 7);
$userId = getCookie("user_id", "guest");
deleteCookie("old_cookie");
?>

Practical Examples

Example 1: Remember Me Functionality
<?php
// login.php
if($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    $password = $_POST["password"];
    $remember = isset($_POST["remember"]);

    // Verify credentials (simplified)
    if($username == "admin" && $password == "password") {
        if($remember) {
            // Set cookie for 30 days
            setcookie("username", $username, time() + (30 * 86400), "/", "", true, true);
        }
        header("Location: dashboard.php");
        exit();
    }
}

// Check for existing cookie
if(isset($_COOKIE["username"])) {
    $savedUsername = $_COOKIE["username"];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <form method="POST">
        <input type="text" name="username" value="<?php echo $savedUsername ?? ''; ?>" placeholder="Username">
        <input type="password" name="password" placeholder="Password">
        <label>
            <input type="checkbox" name="remember"> Remember Me
        </label>
        <button type="submit">Login</button>
    </form>
</body>
</html>
Example 2: User Preferences (Theme Switcher)
<?php
// theme_handler.php
if(isset($_GET['theme'])) {
    $theme = $_GET['theme'];
    if($theme == 'dark' || $theme == 'light') {
        setcookie("user_theme", $theme, time() + (365 * 86400), "/");
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}

$currentTheme = isset($_COOKIE["user_theme"]) ? $_COOKIE["user_theme"] : "light";
?>

<!DOCTYPE html>
<html>
<head>
    <title>Theme Switcher</title>
    <style>
        body.light { background: #fff; color: #000; }
        body.dark { background: #333; color: #fff; }
    </style>
</head>
<body class="<?php echo $currentTheme; ?>">
    <h1>Current Theme: <?php echo ucfirst($currentTheme); ?></h1>
    <a href="?theme=light">Light Theme</a> |
    <a href="?theme=dark">Dark Theme</a>
</body>
</html>
Example 3: Shopping Cart Cookie
<?php
// cart.php
function addToCart($productId) {
    $cart = isset($_COOKIE["cart"]) ? json_decode($_COOKIE["cart"], true) : [];

    if(isset($cart[$productId])) {
        $cart[$productId]++;
    } else {
        $cart[$productId] = 1;
    }

    setcookie("cart", json_encode($cart), time() + (7 * 86400), "/");
}

function getCart() {
    return isset($_COOKIE["cart"]) ? json_decode($_COOKIE["cart"], true) : [];
}

function removeFromCart($productId) {
    $cart = getCart();
    if(isset($cart[$productId])) {
        unset($cart[$productId]);
        setcookie("cart", json_encode($cart), time() + (7 * 86400), "/");
    }
}

function clearCart() {
    setcookie("cart", "", time() - 3600, "/");
}

// Usage
if(isset($_GET["add"])) {
    addToCart($_GET["add"]);
}

$cart = getCart();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart</title>
</head>
<body>
    <h1>Shopping Cart</h1>
    <?php if(empty($cart)): ?>
        <p>Your cart is empty.</p>
    <?php else: ?>
        <ul>
        <?php foreach($cart as $productId => $quantity): ?>
            <li>Product #<?php echo $productId; ?> - Quantity: <?php echo $quantity; ?></li>
        <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <p><a href="?add=101">Add Product 101</a></p>
    <p><a href="?add=102">Add Product 102</a></p>
</body>
</html>
Example 4: Page Visit Counter
<?php
// visit_counter.php
$visits = isset($_COOKIE["visit_count"]) ? (int)$_COOKIE["visit_count"] : 0;
$visits++;

setcookie("visit_count", $visits, time() + (365 * 86400), "/");

$lastVisit = isset($_COOKIE["last_visit"]) ? $_COOKIE["last_visit"] : "Never";
setcookie("last_visit", date("Y-m-d H:i:s"), time() + (365 * 86400), "/");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Visit Counter</title>
</head>
<body>
    <h1>Welcome to Our Website!</h1>
    <p>You have visited this page <strong><?php echo $visits; ?></strong> times.</p>
    <p>Last visit: <strong><?php echo $lastVisit; ?></strong></p>
</body>
</html>

Session Summary

Key Points
  • Cookies are small text files stored on the client's browser for maintaining state
  • Use setcookie() function to create cookies before any output is sent
  • Access cookie values through the $_COOKIE superglobal array
  • Modify cookies by setting them again with the same name
  • Delete cookies by setting expiration time to the past
  • Always implement security best practices: HttpOnly, Secure flags, and encryption
  • Cookies are limited to 4KB of data per cookie
  • Validate and sanitize all cookie data to prevent security vulnerabilities
Next Session Preview

In the next session, we will explore PHP Sessions, which provide a more secure and robust way to maintain user state across multiple pages, storing data on the server rather than the client.