Skip to Content
Course content

189: Practice Exercise: Building a Multi-Step Checkout Flow

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a pull request for a junior dev who had built a checkout process for a niche electronics store. He'd put everything—shipping, billing, payment, and order review—on one massive page. It looked okay on a desktop, but on mobile, users were scrolling for an eternity, and the validation errors were jumping all over the place. When he tried to split it into multiple pages, he hit a wall: the data from the first page kept vanishing when the user hit the "Back" button to fix a typo in their address. He was trying to pass everything through $_POST from page to page, which is a recipe for disaster.

That's where we need to shift our thinking. In a multi-step flow, you aren't just moving data from one script to another; you're managing a state. You need a way to accumulate information over several requests and only commit that data to your database once the user hits that final "Place Order" button. If you write to the database at every step, you'll end up with a graveyard of half-finished "ghost orders" from people who abandoned their carts halfway through.

Managing State with Session-Based Accumulation

The cleanest way to handle this in PHP is by using the $_SESSION superglobal as a temporary staging area. Instead of passing hidden input fields from page to page, you treat the session as a bucket. When the user submits their shipping info on page one, you validate it and then tuck it into a specific key, like $_SESSION['checkout_data']['shipping'].

I usually recommend grouping all checkout data under one top-level session key. It makes cleanup much easier. When the order is finally placed, or if the user decides to cancel, you can just unset($_SESSION['checkout_data']) and clear the slate. It’s much more maintainable than having five different session variables floating around your global namespace.

// Example of accumulating data on the shipping page
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $shippingData = [
        'address' => $_POST['address'] ?? '',
        'city'    => $_POST['city'] ?? '',
        'zip'     => $_POST['zip'] ?? '',
    ];

    if (validateShipping($shippingData)) {
        $_SESSION['checkout_data']['shipping'] = $shippingData;
        header('Location: payment.php');
        exit;
    }
}

Guarding the Flow and Preventing Skip-Ahead

One thing that often gets overlooked is "flow control." You can't just trust that a user will follow your links in order. A savvy user (or a bot) might try to jump straight to confirmation.php by typing the URL into the browser. If your confirmation page assumes the session data is already there, it'll throw a bunch of "Undefined index" notices or, worse, try to process an empty order.

You need a guard clause at the top of every step. I like to write a small helper function that checks if the required data for that specific stage exists. If it doesn't, you boot them back to the start of the flow. It's a simple check, but it saves you from an endless amount of debugging later on. It's essentially a manual way of enforcing a state machine.

The Final Hand-off to the Database

Once the user hits the final confirmation page, you've reached the "commit" phase. This is the only time you should be interacting with your orders and order_items tables. At this point, you gather everything from $_SESSION['checkout_data'], wrap your database insertions in a transaction to ensure atomicity, and then clear the session.

Remember: if the database transaction fails, do not clear the session. You want the user to be able to try again without re-typing their entire shipping address. Only once you receive a success confirmation from the DB should you wipe the checkout state and redirect them to a "Thank You" page.




📋 Practical Task

Exercise: The Secure Three-Stage E-Commerce Checkout Pipeline

Your goal is to build a functional multi-step checkout prototype using PHP sessions. You need to create three separate files: shipping.php, payment.php, and review.php.

  • shipping.php: Create a form that collects a Full Name and Address. On submission, validate that the fields aren't empty and store them in $_SESSION['checkout']['shipping']. Redirect to payment.php.
  • payment.php: Create a form that collects a Credit Card Number (mock) and Expiry Date.
    • Add a guard clause: If $_SESSION['checkout']['shipping'] is not set, redirect the user back to shipping.php with an error message.
    • On submission, store the data in $_SESSION['checkout']['payment'] and redirect to review.php.
  • review.php: This page should not have a form for input, but should display a summary of all the data stored in the session (Shipping and Payment).
    • Add a guard clause: If either the shipping or payment session data is missing, redirect back to the appropriate missing step.
    • Include a "Confirm Order" button that, when clicked, simulates a database save (e.g., echo "Order Processed!";), clears the $_SESSION['checkout'] array, and ends the flow.

Requirement: Ensure session_start() is called at the very top of every file and that you use header('Location: ...') for all transitions.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.