If you are diving into the world of web development, building an e-commerce feature is a rite of passage. It teaches you about state management, handling user input, and processing data. Today, we are going to walk through a complete, beginner-friendly PHP shopping cart tutorial.
By the end of this guide, you will have a functional, session-based shopping cart where users can add products, view their cart, and clear it. No complex frameworks—just pure, vanilla PHP.
We will focus purely on the core logic using PHP sessions, setting the perfect foundation before you connect it to a MySQL database later.
Let's dive in! 🚀
Prerequisites
Before we start coding, make sure you have:
- A local development environment installed (like XAMPP, MAMP, or Laravel Valet).
- Basic knowledge of PHP and HTML.
- A code editor (VS Code is always a solid choice).
Step 1: Setting Up the Products and Session
Because PHP is stateless, it forgets everything about a user as soon as the page loads. To build a shopping cart, we need a way to remember what the user clicked on. Enter PHP Sessions.
Create a file named index.php. At the very top of this file, we will start our session and define a mock array of products. In a real-world application, you would fetch these from a MySQL database.
<?php
session_start();
// Initialize the cart if it doesn't exist
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Mock database of products
$products = [
1 => ['name' => 'Mechanical Keyboard', 'price' => 120.00],
2 => ['name' => 'Wireless Mouse', 'price' => 50.00],
3 => ['name' => 'Monitor Stand', 'price' => 35.00]
];
?>
Step 2: Displaying the Storefront
Now that we have our products, let's display them so users can actually click "Add to Cart". Add this HTML below your PHP logic in index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Shopping Cart Tutorial</title>
<style>
body { font-family: system-ui, sans-serif; padding: 2rem; }
.product { border: 1px solid #ccc; padding: 1rem; margin-bottom: 1rem; border-radius: 8px; }
.btn { background: #3b49df; color: white; border: none; padding: 0.5rem 1rem; cursor: pointer; border-radius: 4px; text-decoration: none;}
.btn:hover { background: #2f3ab2; }
</style>
</head>
<body>
<h1>Awesome Dev Store</h1>
<div class="products-grid">
<?php foreach ($products as $id => $product): ?>
<div class="product">
<h3><?php echo $product['name']; ?></h3>
<p>$<?php echo number_format($product['price'], 2); ?></p>
<!-- We pass the product ID via the URL -->
<a href="cart.php?action=add&id=<?php echo $id; ?>" class="btn">Add to Cart</a>
</div>
<?php endforeach; ?>
</div>
<hr>
<a href="cart.php" class="btn">View Cart (<?php echo count($_SESSION['cart']); ?> items)</a>
</body>
</html>
Step 3: Handling Cart Logic
Now comes the core of our PHP shopping cart tutorial. We need to create a cart.php file that handles three main actions:
- Adding an item.
- Clearing the cart.
- Displaying the cart contents.
Create cart.php and paste the following code:
<?php
session_start();
// Redirect back to index if cart doesn't exist
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Handle Add to Cart action
if (isset($_GET['action']) && $_GET['action'] == 'add') {
$id = intval($_GET['id']);
// If item is already in cart, increase quantity
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id]['quantity']++;
} else {
// Add new item to cart
$_SESSION['cart'][$id] = [
'quantity' => 1
];
}
// Redirect to avoid form resubmission on refresh
header('Location: cart.php');
exit;
}
// Handle Clear Cart action
if (isset($_GET['action']) && $_GET['action'] == 'clear') {
$_SESSION['cart'] = [];
header('Location: cart.php');
exit;
}
// Same mock database for pricing reference
$products = [
1 => ['name' => 'Mechanical Keyboard', 'price' => 120.00],
2 => ['name' => 'Wireless Mouse', 'price' => 50.00],
3 => ['name' => 'Monitor Stand', 'price' => 35.00]
];
?>
Step 4: Displaying the Cart
Finally, let's render the cart in the same cart.php file so the user can see what they are about to buy. Append this HTML to cart.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Cart</title>
<style>
body { font-family: system-ui, sans-serif; padding: 2rem; }
table { width: 100%; border-collapse: collapse; margin-bottom: 2rem;}
th, td { text-align: left; padding: 1rem; border-bottom: 1px solid #ccc; }
.btn { background: #3b49df; color: white; padding: 0.5rem 1rem; text-decoration: none; border-radius: 4px;}
.btn-danger { background: #df3b3b; }
</style>
</head>
<body>
<h1>Your Shopping Cart</h1>
<?php if (empty($_SESSION['cart'])): ?>
<p>Your cart is currently empty.</p>
<?php else: ?>
<table>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody>
<?php
$total = 0;
foreach ($_SESSION['cart'] as $id => $item):
$product = $products[$id];
$subtotal = $product['price'] * $item['quantity'];
$total += $subtotal;
?>
<tr>
<td><?php echo $product['name']; ?></td>
<td>$<?php echo number_format($product['price'], 2); ?></td>
<td><?php echo $item['quantity']; ?></td>
<td>$<?php echo number_format($subtotal, 2); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th colspan="3" style="text-align: right;">Total:</th>
<th>$<?php echo number_format($total, 2); ?></th>
</tr>
</tfoot>
</table>
<a href="cart.php?action=clear" class="btn btn-danger">Empty Cart</a>
<?php endif; ?>
<br><br>
<a href="index.php" class="btn">← Continue Shopping</a>
</body>
</html>
Wrapping Up
And there you have it! You've just completed a working prototype from this PHP shopping cart tutorial.
Next Steps for Production:
While this is a great learning exercise, you will want to upgrade a few things before putting this on a live server:
-
Database Integration: Swap the
$productsarray for PDO or MySQLi queries. - Security: Sanitize your URL inputs to prevent XSS and SQL injection.
- Checkout Gateways: Integrate a service like Stripe or PayPal to handle the actual money.
If you found this tutorial helpful, drop a like or let me know in the comments how you plan to implement this in your next project. Happy coding! 👨💻👩💻
Top comments (0)