PHP Shopping Cart using Sessions
In this lesson: Build a shopping cart in PHP using sessions — add, update quantity, remove and total price — complete source code.
What we are building
A shopping cart remembers what a user wants to buy as they browse. We will build a simple cart using the session, so it survives across pages without a database until checkout. It will add items, update quantities, show the total, and remove items.
$_SESSION["cart"] as an array keyed by product id, each holding a quantity.Starting the cart
<?php
session_start();
if (!isset($_SESSION["cart"])) {
$_SESSION["cart"] = []; // empty cart
}
?>
We start the session and make sure the cart array exists. Every cart page begins like this so the cart is always ready to use.
Add to cart
<?php
$id = (int)$_GET["id"]; // product id
if (isset($_SESSION["cart"][$id])) {
$_SESSION["cart"][$id] += 1; // already there: +1
} else {
$_SESSION["cart"][$id] = 1; // new item
}
echo "Added to cart";
?>
If the product is already in the cart, we increase its quantity; otherwise we add it with quantity 1. Using the id as the key keeps one entry per product.
View the cart and total
<?php
// pretend prices come from the database:
$prices = [1 => 100, 2 => 250, 3 => 90];
$total = 0;
foreach ($_SESSION["cart"] as $id => $qty) {
$line = $prices[$id] * $qty;
$total += $line;
echo "Product $id x $qty = $line\n";
}
echo "Total: $total";
?>
Total: 200
We loop the cart, look up each price from a trusted source, multiply by quantity, and add to the total. Never trust a price sent from the browser.
Remove an item
<?php
$id = (int)$_GET["id"];
unset($_SESSION["cart"][$id]); // remove that product
echo "Removed from cart";
?>
unset deletes that product from the cart array. To empty the whole cart, set $_SESSION["cart"] = [].
Common mistakes
- Trusting prices from the form. Always fetch the real price from the database by id.
- Not casting the id. Cast
$_GET["id"]to(int)for safety. - Duplicate entries. Key the cart by product id and increase quantity instead of adding again.
- Forgetting
session_start(). Every cart page needs it to read the cart.
Summary
- A shopping cart lives in the session while the user browses.
- Store it as an array keyed by product id, each holding a quantity.
- Adding an existing product increases its quantity.
- Calculate the total from trusted database prices, not the browser.
- Use
unsetto remove an item; clear the array to empty the cart.
Next, save the final order with PHP CRUD, or manage the session in sessions and cookies.
