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.
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
$_COOKIEsuperglobal 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.