PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
25: Sessions and Cookies
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.phppage 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.
There are no comments for now.