Skip to content
Tutorials Center
My learning

Topics

Lesson 133 of 147 ยท Projects

Project: Shopping Cart

Build a PHP shopping cart in four stages - money as integer cents, a session cart, coupons with enums and match, tax with bcmath and a transactional checkout.

A shopping cart looks like a list with numbers next to it, and that's exactly why it goes wrong so often. Prices are stored as floats and totals come out a cent off. The cart trusts the price the browser sent, so a clever customer buys a laptop for one dollar. Two customers check out the last item at the same moment and both succeed. A coupon applies twice. Every one of these bugs has happened on real stores, and every one has a simple, well-known fix.

In this project you'll build a cart in four stages, each a complete program. First you'll represent money as integer cents and keep a basic cart in a session array. Then you'll wrap it in a Cart class that validates every change against the product catalog. Then you'll add discount rules with an enum and match, shipping, and sales tax calculated exactly with bcmath. Finally you'll turn the cart into an order inside a database transaction that checks and reduces stock safely.

Our editor runs PHP on the command line, so there's no browser and no real session. A plain array stands in for $_SESSION, and stage 4 simulates the shop's requests (add to cart, apply a coupon, check out) by calling the handler functions directly. The prices, products and coupons are invented for the demo.

The plan

  • Products have a SKU (stock-keeping unit, the product code), a name, a price in cents and a stock count.
  • The cart stores only SKUs and quantities: ['MUG-01' => 2, 'TEE-M' => 1]. Prices are always looked up in the catalog on the server, never taken from the request or remembered in the session. If a price changes while an item sits in a cart, the cart shows the new price, and checkout charges it.
  • Totals are calculated in one place, in this order: subtotal โ†’ discount โ†’ shipping โ†’ tax โ†’ total.
  • Checkout creates an order that stores a snapshot of each price, so old orders keep the amounts the customer actually paid.

Stage 1: money as integer cents

Before writing any cart code, look at why money must not be a float. Binary floating-point numbers can't represent most decimal fractions exactly, as the Integers and Floats lesson explains. The errors are tiny, but money code compares, truncates and adds thousands of values, and tiny errors become wrong cents:

PHP Why prices are never floats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

0.1 + 0.2 is 0.30000000000000004, so comparing it with 0.3 gives false. Converting 19.99 to cents with (int) ($price * 100) gives 1998, because the product is 1998.9999999999998 and the cast truncates. Adding ten cents a thousand times drifts to 99.9999999999986. Integers have none of these problems: 1,000 times 10 cents is exactly 10000 cents, 100.00.

So every amount in this project is an int number of cents. The only place a decimal point appears is formatMoney, which builds the string with integer division (intdiv) and remainder (%), so no float is involved even for display. For amounts that need fractions of a cent, like tax rates, stage 3 uses the bcmath extension, which calculates with decimal strings of any precision.

The first cart is an array of sku => quantity in the session. addToCart adds to the existing quantity, cartLines joins the cart with the catalog to get names and prices, and the subtotal is the sum of the line totals.

PHP Stage 1: a session cart with integer cents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first cart has two mugs ($29.00), a notebook ($8.99) and four pens ($15.00), for a subtotal of $52.99. After adding two more notebooks, removing the pens and adding a T-shirt, it's $77.96. The session holds nothing but {"cart":{"MUG-01":2,"NB-A5":3,"TEE-M":1}}: no names, no prices. The last line checks formatMoney with a large amount, a few cents and a negative amount: $1,234,567.89 $0.05 -$2.50.

array_sum(array_column($lines, 'total')) is a compact way to add up one column of a list of rows. See Multidimensional Arrays.

This first version trusts its callers completely. addToCart($session, 'LAPTOP', -5) would happily store a negative quantity of a product that doesn't exist, and cartLines would then crash on the unknown SKU. On a real site, the SKU and quantity come from a form, which means from anyone. Stage 2 fixes that.

Stage 2: a Cart class with validation

The cart becomes a class with a small, strict interface: add, setQuantity and remove. Every method checks its input against the catalog before changing anything and throws a CartError with a message the shop can show the customer:

  • The SKU must exist in the catalog.
  • Quantities must be whole numbers from 1 to 10 per product (setting 0 removes the item).
  • The cart can't hold more of a product than is in stock.

Products are now readonly objects of a Product class, and the Catalog looks them up by SKU. The cart loads from the session at the start of a request and saves back to it at the end, with Cart::fromSession() and toSession(). Keeping the session handling at the edges means the Cart class itself knows nothing about sessions and can be tested on its own.

Converting a form value to a quantity is the job of parseQuantity. Form fields are strings like '3', and filter_var with FILTER_VALIDATE_INT turns them into integers while rejecting '2.5', '3 mugs' and ''. Under strict_types, passing the string '3' straight to add(string $sku, int $quantity) would throw a TypeError, which is the right reaction for a programming mistake but not for a typo in a form. (Type Juggling and Casting explains what strict_types changes.)

PHP Stage 2: a validating Cart class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The cart starts with two notebooks from an earlier request. Three mugs are accepted. Four T-shirts are refused because only 3 are in stock, while two are fine. The unknown SKU, the negative quantity and 2.5 are each refused with a specific message, and none of them changes the cart. Nine notebooks are accepted, and quantity 0 removes the notebooks completely. The session ends up as {"cart":{"MUG-01":3,"TEE-M":2}}.

A detail that matters: when a request fails, toSession isn't called, so the session keeps the state from before the request. The Cart is rebuilt from the session at the start of every simulated request, as it would be on a server.

The stock check in the cart is a courtesy, not a guarantee. Another customer can buy the last T-shirts while yours sit in the cart. The real check happens at checkout, inside a transaction, in stage 4.

Stage 3: discounts, shipping and tax

Now the totals get interesting. The shop offers three kinds of coupons, which map naturally to a backed enum:

PHP
enum DiscountKind: string
{
    case Percent = 'percent';
    case Fixed = 'fixed';
    case FreeShipping = 'free_shipping';
}

A Coupon combines a kind with a value and a minimum subtotal, and a match expression on the kind calculates the discount. Because match is exhaustive, adding a fourth kind later without handling it would throw an UnhandledMatchError the first time it's used, instead of quietly giving no discount. The switch and match lesson covers the details.

The calculation runs in a fixed order, implemented in one function, calculateTotals:

  1. Subtotal: the sum of the line totals.
  2. Discount: a percentage, a fixed amount (never more than the subtotal), or nothing for free-shipping coupons. Percentages are rounded to the nearest cent, half up, with integer arithmetic: intdiv($subtotal * $percent + 50, 100).
  3. Shipping: a flat $5.99, free when the discounted subtotal is $50.00 or more, or with a free-shipping coupon.
  4. Tax: 8.875% of the discounted subtotal plus shipping. A rate with three decimals is where integer cents alone get awkward, so the tax is calculated with bcmath: bcmul multiplies decimal strings exactly, and bcround (PHP 8.4) rounds the result to whole cents.
  5. Total: subtotal minus discount plus shipping plus tax.

The result is a readonly Totals object, so nothing can change a total after it's calculated. Coupon codes are matched case-insensitively after trimming, since customers type save10 as often as SAVE10.

PHP Stage 3: coupons with enums, tax with bcmath

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at a few of the results:

  • The small order of $23.49 pays $5.99 shipping and $2.62 tax ($29.48 ร— 8.875% = $2.6163, rounded to $2.62), for a total of $32.10.
  • 10% off $47.90 is $4.79. The discounted $43.11 is under $50, so shipping applies.
  • 10% off $52.00 is $5.20, which brings the subtotal down to $46.80, under the free-shipping threshold. Because shipping is decided after the discount, this order pays shipping, which is the rule most shops use. (Deciding before the discount would also be a valid policy; what matters is that it's written down in one place.)
  • WELCOME5 on $17.99 isn't applied, and the note explains why. On $30.00 it takes $5.00 off.
  • SHIPFREE gives no discount on the items but removes the shipping.

The match ($coupon?->kind) line combines two operators: the nullsafe operator ?-> gives null when there's no coupon, and the null arm handles that case together with FreeShipping. The last two lines show the enum helpers: from('fixed') returns the Fixed case, and tryFrom('bogus') returns null instead of throwing.

bcround and the RoundingMode enum arrived in PHP 8.4. On older versions, the usual trick is bcadd($value, '0.5', 0) for positive amounts, which adds half a cent and truncates. PHP 8.4 also added the BcMath\Number class, which supports operators: new BcMath\Number('29.48') * '0.08875'. See Math Functions.

Stage 4: checkout and the order summary

At checkout the cart becomes an order. This is where the money is real, so the code is careful in a few specific ways.

Prices come from the database at checkout. The order stores each item's unit price and name as they are at that moment. If the shop raises the price of mugs next month, this order still says $14.50, because the order_items table has its own copy. Never join old orders to the current product table to show what a customer paid.

Stock is reduced atomically. The statement

SQL
UPDATE products SET stock = stock - :qty WHERE sku = :sku AND stock >= :qty

changes the row only if enough stock is left, and rowCount() tells us whether it did. Checking stock with a SELECT and then updating it in a second statement leaves a gap in which another customer could buy the same items; the single conditional UPDATE closes it.

Everything happens in one transaction. Creating the order, adding its items and reducing the stock of every product either all succeed or all roll back. If the third product turns out to be sold out, the stock of the first two is restored and no half-finished order is left behind. Transactions explains beginTransaction, commit and rollBack.

The cart is emptied only after the commit. If checkout fails, the customer keeps their cart and sees a message.

The handler functions take the session array by reference and return a short message, so the demo can simulate a whole shopping trip: adding items, trying a coupon, checking out, and a second customer who arrives too late for the last T-shirts. Both customers' sessions live in one $sessions array, and for each step $session = &$sessions[$who] makes $session a reference to the right one, so the handlers' changes land in it. unset($session) afterward breaks the reference before the next step, the same precaution you take after a by-reference loop in foreach Loops.

PHP Stage 4: a transactional checkout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Alice puts the last two T-shirts in her cart, and Bruno adds a mug and one T-shirt. The cart allows that, because when Bruno clicks, the stock still says 2. Alice's attempt to add 50 notebooks is refused (the limit is 10), halfprice is an unknown coupon, and save10 is accepted after trimming and uppercasing.

Alice checks out first and gets order #1. Her summary shows two T-shirts at $21.99 and a mug at $14.50: a subtotal of $58.48, a 10% discount of $5.85, free shipping because $52.63 is over $50, and $4.67 tax, for a total of $57.30.

Then Bruno checks out. His mug can be reserved, but the T-shirt update finds stock >= 1 false and changes no row, so CheckoutError is thrown and the transaction rolls back. His mug goes back into stock, no order #2 exists, and his cart is untouched so he can remove the T-shirt and try again. At the end, the stock is MUG-01: 24, NB-A5: 40 and TEE-M: 0, and exactly one order is saved.

Notice the CHECK (stock >= 0) constraints in the schema. They're a second line of defense: even if a future change to the PHP code forgot the stock >= :qty condition, the database would refuse to store a negative stock.

orderSummary puts $orderId straight into the SQL string. That's safe only because the parameter is declared int, so with strict_types nothing else can reach it. As soon as an id comes from a URL, use a placeholder, as the line after it does. When in doubt, always use a placeholder; it costs nothing.

Running it on a real server

On a server, the session arrays become $_SESSION, and each step is a form post handled by one script. A typical "Add to cart" handler looks like this:

PHP
<?php

declare(strict_types=1);

session_start();
require __DIR__ . '/../src/shop.php';   // addToCart(), checkout(), ...

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrfToken($_POST['csrf_token'] ?? null)) {
    $sku = is_string($_POST['sku'] ?? null) ? $_POST['sku'] : '';
    $quantity = filter_var($_POST['quantity'] ?? '', FILTER_VALIDATE_INT) ?: 0;

    $_SESSION['flash'] = addToCart($pdo, $_SESSION, $sku, $quantity);
}

header('Location: /cart', true, 303);   // POST-redirect-GET

Note what the form does not send: a price. The product page form contains only the SKU, the quantity and a CSRF token:

HTML
<form method="post" action="/cart/add">
  <input type="hidden" name="csrf_token" value="...">
  <input type="hidden" name="sku" value="MUG-01">
  <input type="number" name="quantity" value="1" min="1" max="10">
  <button>Add to cart</button>
</form>

Sessions are stored per visitor, so a cart lives only as long as the session (often until the browser closes). Stores that want carts to survive for weeks, or to follow a logged-in user to another device, keep them in a carts table keyed by user id instead, using the login system to know who the user is.

Payment itself is handed to a payment provider (Stripe, Paddle, PayPal, Adyen and others). Your server creates a payment for the order total, redirects the customer to the provider's page and marks the order as paid only when the provider confirms it through a signed webhook request. Never handle card numbers yourself.

Ideas for extending the cart

  • Product options like size and color, with a separate SKU per combination.
  • Quantity discounts ("3 for 2") as a new DiscountKind case; the exhaustive match will point you to every place that needs updating.
  • Per-country tax rates and shipping zones, looked up from the shipping address.
  • Single-use coupons: a coupon_redemptions table checked and written inside the checkout transaction, with a UNIQUE constraint so a coupon can't be redeemed twice, even by two simultaneous checkouts.
  • Order emails sent through the Mailer interface from the contact form project, after the commit.
  • A JSON cart API built like the REST API project, for a JavaScript front end.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (int) (19.99 * 100) give in PHP?

    19.99 can't be stored exactly, so the product is 1998.9999999999998, and the int cast truncates it to 1998. That's why prices are stored as integer cents from the start.
  2. 2. Where does the cart get the price of each item?

    Anything the browser sends can be changed by the customer, and prices saved in the session go stale. The session stores only SKUs and quantities.
  3. 3. Why does checkout use UPDATE products SET stock = stock - :qty WHERE sku = :sku AND stock >= :qty?

    A separate SELECT and UPDATE leave a gap where another checkout can slip in. The conditional UPDATE changes the row only if enough stock is left, and rowCount() tells you whether it did.
  4. 4. In stage 4, Bruno's T-shirt is sold out when he checks out. What happens to the mug he also ordered?

    The order, its items and all stock changes are in one transaction. The CheckoutError triggers rollBack(), which undoes everything, and Bruno's cart is left unchanged.
  5. 5. Why is the free-shipping threshold checked after the discount is subtracted?

    Either order is a valid business rule, and it can change the total. What matters is that calculateTotals applies the steps in one documented order.

Summary

  • Store every amount as an integer number of cents; format with intdiv and %, and use bcmath (bcmul, bcround in PHP 8.4) for rates with fractions of a cent.
  • Keep only SKUs and quantities in the session; look up prices and stock on the server every time.
  • Validate every cart change against the catalog: known SKU, a whole-number quantity in range, enough stock. Convert form strings with filter_var.
  • Model discount types as a backed enum and calculate them with an exhaustive match; apply subtotal, discount, shipping and tax in one fixed order.
  • At checkout, use one transaction for the order, its items and the stock changes, reduce stock with a conditional UPDATE checked by rowCount(), and store a snapshot of each price.
  • Empty the cart only after a successful commit, and hand real payments to a payment provider.

Next: Project: Group Chat with Polling.