-
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
62: Practice Exercise: Building a Session-Based Shopping Cart
Think of a session-based shopping cart like a waiter with a notepad at a restaurant. The waiter doesn't memorize every single request from every table in the room—that's a recipe for disaster. Instead, they carry a small pad of paper. When you tell them you want a burger, they scribble it down. When you decide you also want a side of fries, they add it to the list on that same piece of paper. The notepad stays with your table until you pay the bill and leave. If the waiter forgets who you are, the notepad is what tells them exactly what you've ordered so far.
In PHP, the $_SESSION superglobal is that notepad. The server is the waiter, and the session ID (stored in a cookie on the user's browser) is the table number. Without the session, PHP is "stateless," meaning it forgets who the user is the second the page finishes loading. By using $_SESSION, we can "scribble down" product IDs and quantities and have them still be there when the user navigates to the checkout page.
The Mental Model for Cart Data
I've seen a lot of beginners try to store the entire product object—name, price, description—directly in the session. Don't do that. It's a bad habit. If you change a product's price in your database, but the user has the old price saved in their session, you're going to have a headache. Instead, only store the Product ID and the Quantity.
I prefer using the product ID as the key in an associative array. It makes updating quantities a breeze. Here is how I'd structure the session data:
$_SESSION['cart'] = [
'prod_123' => 2, // 2 units of product 123
'prod_456' => 1 // 1 unit of product 456
];
Handling the 'Add to Cart' Logic
When a user clicks "Add to Cart," you aren't just adding a row to a list; you're checking if that item already exists in the "notepad." If it does, you just bump the number up. If it doesn't, you create the entry.
Here is a clean way to handle this logic. I'm assuming you're getting the product ID from a $_POST request:
session_start();
$productId = $_POST['product_id'];
// If the cart doesn't exist yet, initialize it as an empty array
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// If the item is already in the cart, increment the quantity.
// Otherwise, set it to 1.
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId]++;
} else {
$_SESSION['cart'][$productId] = 1;
}
Tallying the Bill
Since we only stored the IDs and quantities, the "Checkout" page needs to do some heavy lifting. You'll need to loop through your session array, fetch the current price for each ID from your database (or a mock product array), and multiply it by the quantity.
I usually write a helper function for this to keep the HTML clean. Something like this:
function calculateTotal($cart, $productCatalog) {
$total = 0;
foreach ($cart as $id => $quantity) {
if (isset($productCatalog[$id])) {
$total += $productCatalog[$id]['price'] * $quantity;
}
}
return $total;
}
One quick tip: always remember to call session_start() at the very top of every single file that touches the cart. If you forget, your notepad disappears, and your users will be very confused why their cart keeps emptying itself.
📋 Practical Task
Exercise: The Vintage Vinyl Store Cart
Your goal is to build a functional prototype of a shopping cart for a record store. You don't need a database for this; a hard-coded associative array acting as your "catalog" will work perfectly.
- The Catalog: Create an array called
$productswhere the keys are IDs (e.g., 'vinyl_01') and the values are arrays containing 'name' and 'price'. - The Storefront: Create a page that lists these records with an "Add to Cart" button for each. This should send the ID via a POST request to a processing script.
- The Cart Logic: Implement the session logic we discussed. If a user adds the same record twice, the quantity in
$_SESSION['cart']should increase. - The Review Page: Create a
cart.phppage that:- Displays the name of each item in the cart.
- Displays the quantity of each item.
- Calculates and displays the subtotal for each line item and the final grand total for the whole order.
- The Clear Action: Add a "Empty Cart" button that uses
unset($_SESSION['cart'])to wipe the notepad clean.
There are no comments for now.