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
193: Building a Shopping Cart Session Manager
We've touched on how sessions work in a vacuum, but now it's time to put them to work in a scenario you'll encounter in almost every e-commerce project: the shopping cart. The challenge here isn't just storing data, but managing a state that changes as the user browses. We need a way to add items, update quantities, and keep that data persistent across different pages without hitting the database every single time a user clicks "Add to Cart".
Structuring the Cart in the Session
I prefer to keep the cart as an associative array inside the $_SESSION superglobal. The key should be the product ID, and the value should be the quantity. This makes it incredibly easy to check if an item is already in the cart without looping through the whole list. If the ID exists as a key, we just increment the value.
The "Wipeout" Mistake
Now, here is where I messed up the first time I built this years ago. I tried to be "efficient" by writing the addition in a single line, thinking I could just assign the value directly. I wrote something like $_SESSION['cart'] = [$productId => $quantity];.
Of course, that was a disaster. Every time a user added a second item to their cart, the first item vanished. I wasn't appending to the array; I was overwriting the entire cart with a new array containing only the most recent item. It's a classic "junior" mistake, but it happens to the best of us when we're rushing. The key is to remember that $_SESSION is just a persistent array—treat it with the same care you'd treat any other PHP array.
Calculating Totals from Session Data
Once the items are in the session, the next step is actually making them useful. You don't want to store prices in the session because prices change in the database, and a user could potentially manipulate their session data to get a discount. Instead, we store the IDs and quantities in the session, then fetch the current prices from our "database" (or a mock array for this example) during the checkout phase.
['name' => 'Mechanical Keyboard', 'price' => 89.99],
102 => ['name' => 'Gaming Mouse', 'price' => 45.00],
103 => ['name' => 'UltraWide Monitor', 'price' => 320.00],
];
$cart = $_SESSION['cart'] ?? [];
$grandTotal = 0;
echo "Your Cart
";
foreach ($cart as $id => $quantity) {
if (isset($products[$id])) {
$itemTotal = $products[$id]['price'] * $quantity;
$grandTotal += $itemTotal;
echo "- {$products[$id]['name']} x $quantity: $" . number_format($itemTotal, 2) . "
";
}
}
echo "
Total: $" . number_format($grandTotal, 2) . "";
?>
By keeping the session lean—only storing IDs and quantities—we keep the session file size small and ensure that the price is always pulled from the source of truth right before the user pays.
📋 Practical Task
Implementing the Cart Item Removal System
Your task is to extend the CartManager class we built in this lesson. Currently, we can add items, but we can't remove them. Create a new method inside the CartManager class called remove($productId) that deletes a specific product from the session cart using unset(). Additionally, create a method called clear() that completely empties the cart. Test your code by adding three different items to the session and then removing only one of them to ensure the others remain intact.
There are no comments for now.