Skip to Content
Course content

25: Sessions and Cookies

Click on the "Edit" button in the top corner of the screen to edit your slide content.

HTTP is fundamentally forgetful. Every time a browser requests a page from your PHP script, the server has absolutely no idea if that request came from a brand new visitor or someone who was just on the previous page two seconds ago. To build anything beyond a static brochure site—like a shopping cart or a user profile—we have to find a way to "remember" who is who.

The temptation to trust the client

When I first started out, the most intuitive approach seemed to be using cookies for everything. If you're building a simple bookstore, you might think, "I'll just store the user's shopping cart directly in a cookie." It seems efficient; the client holds the data, and your server doesn't have to store anything. It looks something like this:

// The naive way: storing data in a cookie
$cart = ['book_id' => 101, 'quantity' => 1];
setcookie('shopping_cart', json_encode($cart), time() + 3600);

On the surface, this works. The next time the page loads, you just json_decode($_COOKIE['shopping_cart']) and you have your list. But here is where it breaks: you are trusting the user. I can open my browser's developer tools, find that cookie, and change the book_id to something else, or worse, if you were storing a total_price in there, I could simply change it to 0.01. Never trust any data that comes from the client. Cookies are essentially "sticky notes" that the user is allowed to rewrite at any time.

Moving the source of truth to the server

This is where sessions come in. Instead of handing the user the actual data, you store the data on the server and give the user a "claim check"—a unique, random session ID. The browser stores this ID in a cookie, but the actual values stay safely in a file or database on your server where the user can't touch them.

// The professional way: using sessions
session_start();

// This data lives on the server, not in the user's browser
$_SESSION['cart'] = ['book_id' => 101, 'quantity' => 1];
$_SESSION['user_id'] = 42;

Now, when the user returns, session_start() looks at the session ID cookie, finds the corresponding file on the server, and populates the $_SESSION superglobal. The user knows they have a session, but they have no way to manipulate their user_id to impersonate someone else or change their cart total. I always tell my juniors: if the data has any value or security implication, it belongs in a session.

When a cookie is actually the right tool

You might be wondering if cookies are useless now. Not at all. The trade-off here is persistence versus security. Sessions typically expire when the browser closes (depending on your PHP settings), and they consume server resources. If you have a million active users, that's a million session files on your disk.

Cookies are perfect for non-sensitive, long-term preferences. For example, if your bookstore has a "Dark Mode" toggle, storing that in a session is overkill. If the user closes their browser and comes back a week later, they'll be annoyed if the site flashes bright white because the session expired. A cookie is the right tool here because it doesn't matter if the user changes theme=dark to theme=light manually; it doesn't break your business logic or compromise security.

// Using a cookie for a non-sensitive preference
if (isset($_GET['theme']) && $_GET['theme'] === 'dark') {
    setcookie('user_theme', 'dark', time() + (86400 * 30), "/"); // Lasts 30 days
}

In short: use sessions for "Who is this person and what are they doing?" and use cookies for "How does this person like their interface to look?"




📋 Practical Task

Build a Persistent Theme Switcher and a Secure Guest Cart

Create a PHP application consisting of two pages: index.php and cart.php.

  • The Theme Switcher: Implement a link or button that toggles a "theme" (e.g., 'light' or 'dark'). This preference must be stored in a cookie so that it persists even after the browser is restarted. The page background color should change based on this cookie.
  • The Guest Cart: Implement a "Add to Cart" button for a dummy product. This product must be stored in a session.
  • The Cart Page: Create a cart.php page that displays the items currently in the session. Ensure that if the session is empty, it displays a "Your cart is empty" message.
  • The Security Test: Try to manually edit the cookie in your browser's developer tools to change the theme; observe that it works. Then, try to find where the cart data is stored in the browser; you should find only a session ID, and no actual product data.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.