Demo mode This site is not live. It is currently being tested and developed. Nothing on here represents an offer.
← Exit course SEC-302 Website and E-Commerce Security
Course progress, 0 of 15 parts done0%

Set up the practice web shop

Download as PDF

A sound skeleton of the shop on your own computer

Table Bay Online and everyone in it are invented for this course, and so is every product, order, person and address in the examples. Real software, standards and laws, such as PHP and the Cybercrimes Act, are named only for what they really are and say.

1. What you will build, and the rule you work by

Naledi Mahlangu owns Table Bay Online, a small online retailer in Salt River, Cape Town, that sells homeware and kitchen goods from South African makers. She is relaunching the web shop on a new server. Palesa, a freelance web developer, has written a first draft of the new shop, and it works. Before customers trust it with their names, addresses and orders, Naledi wants it built to a standard she can rely on. That is your job in this course.

The live shop will do what most small web shops do. Customers browse, make an account, fill a cart and pay on a hosted payment provider's page, so card details never touch Table Bay Online's server. The shop keeps each customer's name, delivery address, phone number, email address and order history in its database. Stock feeds arrive from makers such as Saltpan Ceramics, a pottery in Stanford, and Dwarsrivier Linen in Paarl, and a courier's booking API arranges deliveries. Jason Petersen, who runs operations and customer service, looks after the shop's day-to-day settings.

You will not touch the real shop. You build a practice copy of it on your own computer, small enough to type from the listings in these modules. It starts in this module as a skeleton: a product list, a product page and a cart. Each module after this one adds a part, until in Module 8 you review the finished shop before its launch.

Browser customers and staff The shop: public/index.php and src/ Catalogue, product page, cart M0 Sign-in, sessions, roles, ownership M2 Search, validation, encoding, uploads M3 Form tokens, headers, safe errors M4 Checkout, orders, webhook, refunds M5 Security log and alerts M7 Hosted payment page Module 5 Courier's booking API live shop only Database data/, Module 0 Uploads storage/, Module 3 The whole shop: Module 1 plans it Module 6 deploys it Module 8 reviews it
Figure 1. The finished practice shop, each part labelled with the module that builds it. This module builds the parts marked M0: the catalogue, the product page, the cart and the database.

How the course works

Every module from Module 2 to Module 7 works in the same three steps, and Module 8 uses all three on the finished shop.

Table 1. The three steps in every module
StepWhat you doWhat you keep
1. BuildAdd the module's part to your shop by hand, in plain PHP, written securely from the first line.A working part of the shop.
2. CheckAdd checks to tools/checks.php that show each control working, such as "a request without a valid token is refused with 403", and run them.A growing set of checks that pass.
3. ReviewRead short fragments, a few lines each, from Palesa's first draft, each beside its corrected version. Name the kind of mistake, say why it matters and write the fix yourself.An eye for the common mistakes in other people's code.

The review fragments are not there to blame anyone. Palesa is a capable developer working to a deadline, and each fragment is a mistake any developer can make. Spotting them quickly in someone else's code is a large part of security work. Every task in every module has a full model answer, so you check your own work as you go.

A check in this course is always a positive check: it states what a working control does and confirms it on your own shop. "An unknown product returns 404" is a positive check. You never write or run instructions for breaking into anything, and nothing in the course shows how to abuse a mistake. It explains, in plain words, why each mistake matters.

The rule you work by

You test only your own practice shop, or systems that you own or that you have the owner's written permission to test. Not a live shop, not a supplier's site, not a payment provider, and not a site you only suspect is weak. Checking that something is protected, without permission, can look exactly like trying to get past the protection, to its owner and to the law.

What the law says

Section 2 of the Cybercrimes Act 19 of 2020 makes it an offence to access a computer system unlawfully and intentionally.

Cybercrimes Act 19 of 2020, section 2 (unlawful access)

Sending requests to someone else's website to see what it will let you do, without the owner's permission, can be exactly that. Good practice, which this course follows, is to have the owner's permission in writing before you test anything that is not yours, and to stay within what it allows.

Your practice shop runs at http://localhost:8000, which only your own computer can reach. Everything you build, check and review in this course happens there.

Why plain PHP, and why this shop

You already know PHP if you have done Front-End Web Development with JavaScript (WEB-201) and some server-side work, or Full-Stack Web Development with PHP and Laravel (WEB-301). In WEB-301 a framework provided most of the security controls for you, which is the right way to work on a large project. Here you write each control yourself in plain PHP, so you see the mechanism a framework hides. That is a deliberate choice, not a criticism of frameworks: once you have built a form token by hand, you know what to look for in any framework's version of it.

The shop needs only PHP and its SQLite extension, so there is almost nothing to install. A course file carries no downloads, so the shop is kept small enough to give as listings. And each part you build maps onto a real feature of a web shop like Table Bay Online's.

The skeleton you build in this module is written securely from the start, with nothing weak planted in it and nothing left open. It uses four habits you will meet in full later: prepared statements for every query (Module 3), encoding every value it prints (Module 3), sound settings for the session cookie (Module 2) and a form token on every form that changes something (Module 4). In this module you use them, and the comments in the code say where each is explained.

2. What you need

  • A computer running a supported version of Windows, macOS or Linux, on which you may install software.
  • PHP 8.4 or later, with its PDO SQLite extension, pdo_sqlite.
  • A terminal: PowerShell or Windows Terminal on Windows, Terminal on macOS, any terminal on Linux.
  • A code editor, such as Visual Studio Code, or any editor that saves plain text.
  • A browser with developer tools: Firefox, Chrome or Edge.

Which PHP version

PHP's own site lists which versions are supported. On 10 November 2026 it showed four:

Table 2. Supported PHP versions on 10 November 2026 (php.net)
VersionFirst releasedBug fixes untilSecurity fixes untilFor this course
8.520 November 202531 December 202731 December 2029Recommended
8.421 November 202431 December 202631 December 2028Works
8.323 November 2023Ended31 December 2027Too old
8.28 December 2022Ended31 December 2026Too old

The newest releases on that date were PHP 8.5.12 and 8.4.27, published on 21 October 2026 as security releases that fixed two critical vulnerabilities. Install the newest release of 8.5 if you can, or of 8.4. PHP 8.6 was still a release candidate, a test version, so do not use it for this course. Whatever you install, keep it updated: PHP is software your shop depends on, and Module 6 deals with keeping dependencies current.

PHP's download page, https://www.php.net/downloads.php, asks which operating system you use and gives the steps for it. Here is what it gave on 10 November 2026.

Installing PHP on Windows

  1. On the download page, choose Windows, ZIP Downloads and version 8.5. Under VS17 x64 Non Thread Safe, download the Zip (on 10 November 2026, php-8.5.12-1-nts-Win32-vs17-x64.zip). The page says these builds need the Visual C++ Redistributable for Visual Studio 2015-2022, and links to it. Install that first if you do not have it.
  2. Unzip the file into a new folder, C:\php.
  3. Add that folder to your path: open Start, type "environment variables", choose Edit environment variables for your account, select Path, then Edit, New, type C:\php, and select OK twice.
  4. In C:\php, copy php.ini-development to a new file named php.ini. Open it in your editor, find the lines ;extension_dir = "ext" and ;extension=pdo_sqlite, and delete the character at the start of each, so that PHP loads the SQLite extension.
  5. Open a new PowerShell window, so that it reads the new path, and run php -v.

The download page also offers Winget, Chocolatey, Scoop and WSL (Linux inside Windows). Any of them works, as long as php -v shows 8.4 or later and php -m lists pdo_sqlite.

Installing PHP on macOS

Recent versions of macOS do not include PHP. The download page uses Homebrew, a package manager for macOS: install Homebrew by following the one command on https://brew.sh, then run:

brew install php@8.5
brew link --force --overwrite php@8.5
php -v

Homebrew's PHP includes the SQLite extension, so there is nothing more to switch on.

Installing PHP on Linux

Use your distribution's own packages when they are new enough. Install just the command-line program and the SQLite extension: the package named plain php can also pull in a web server you do not need.

  • Ubuntu 26.04 packages PHP 8.5 and Debian 13 packages PHP 8.4. On either, run sudo apt install php-cli php-sqlite3.
  • Ubuntu 24.04, and distributions built on it such as Linux Mint 22, package PHP 8.3, which is too old. PHP's download page (choose Linux, Ubuntu, version 8.5) gives the commands to add the ppa:ondrej/php package repository. After those, install sudo apt install php8.5-cli php8.5-sqlite3.
  • Other distributions: choose Linux, your distribution and version 8.5 on the download page for its commands.

Check your PHP

In a terminal, on any system:

php -v      # the version: 8.4 or later
php -m      # the extensions: look for PDO and pdo_sqlite
php --ini   # which php.ini file PHP has loaded, if any

If pdo_sqlite is not in the list, the shop cannot open its database, and the first page you load will say could not find driver. Fix it now, as the install steps for your system say.

SQLite

SQLite is a database that lives in a single file, with no database server to install or run. PHP reaches it through the pdo_sqlite extension you have just checked, so for the shop itself there is nothing more to install. If you want to look inside the database file yourself, the sqlite3 command-line program is useful but optional: macOS includes it, Linux installs it with sudo apt install sqlite3, and Windows users can download the command-line tools from https://www.sqlite.org/download.html.

The browser's developer tools

Firefox, Chrome and Edge all have developer tools built in. Open them with F12, or Ctrl+Shift+I on Windows and Linux and Cmd+Option+I on a Mac. You will use two of their tabs: Network, which lists every request the page makes, and Storage in Firefox or Application in Chrome and Edge, which shows the cookies a site has set. Section 6 walks through both.

Warning

PHP's built-in web server is for development only. PHP's manual says it "is not intended to be a full-featured web server. It should not be used on a public network." It runs a single process and has none of a real web server's protections. Start it on localhost, as this course always does, so that only your own computer can reach it, and never on a public address. Module 6 plans how the live shop runs on a real web server.

3. The shop's shape

The shop lives in one folder, practice-shop, with six folders inside it. Figure 2 shows them.

practice-shop/ src/ config, db, helpers, security, pages public/ index.php style.css migrations/ 000_products.sql data/ shop.sqlite tools/ setup.php, checks.php storage/ uploads, logs (later) Browser served never served Started with -t public, only public/ is served
Figure 2. The shop's folders. Only public/ is the web root. The code, the database and, from Module 3, the uploads and logs sit outside it, where no browser can fetch them.

The folder a web server hands out to browsers is its web root, also called the document root. When you start PHP's server with -t public, the public/ folder is the web root, and a browser can ask only for what is inside it. That folder holds just two files: index.php, through which every page request passes, and the stylesheet.

Everything else is outside it. src/ holds the code. data/ holds the database, which tools/setup.php creates. migrations/ holds the SQL that creates each table, and tools/ holds the scripts you run from the terminal. From Module 3, storage/ holds uploaded product pictures and logs.

This layout is itself a security control. If the database file sat inside the web root, anyone who guessed its address could download it, with every customer's details in it. Outside the web root, a slip elsewhere in the shop cannot expose it by a simple download. The router adds a second line: it answers 404 to every address except the shop's own front page, so a request for a file outside public/ gets the shop's own "Not found" page, never the file.

4. Build the skeleton

Make the folders first. In a terminal, go to where you keep your work, such as your Documents folder, then run one of these:

# macOS and Linux
mkdir -p practice-shop/public practice-shop/src/pages practice-shop/migrations practice-shop/tools

# Windows PowerShell
mkdir practice-shop\public, practice-shop\src\pages, practice-shop\migrations, practice-shop\tools

Now create each file below in your editor, with exactly the name shown, and type or copy the listing into it. Typing teaches you more, and copying is quicker. Either way, read each listing and its note before moving on. The comments in the code are short and point to the module that explains each control.

src/config.php: the settings

<?php
declare(strict_types=1);

// The shop's settings. Development is the default.
// Module 6 moves anything secret out of this file.

function config(string $key): mixed
{
    $settings = [
        'env'       => 'development',
        'shop_name' => 'Table Bay Online',
        'db_path'   => dirname(__DIR__) . '/data/shop.sqlite',
    ];
    if (!array_key_exists($key, $settings)) {
        throw new InvalidArgumentException("Unknown setting: $key");
    }
    return $settings[$key];
}

One function, config(), gives every other file its settings, and an unknown name is an error rather than a silent blank. The shop runs in development by default. In Module 6 you move the secrets the shop will have by then out of the code and into a file that is never committed, and this function reads them from there.

src/db.php: the database

<?php
declare(strict_types=1);

// The database: one SQLite file in data/, outside the web root.

function db(): PDO
{
    static $pdo = null;
    if ($pdo === null) {
        $path = config('db_path');
        if (!is_file($path)) {
            throw new RuntimeException('No database. Run: php tools/setup.php');
        }
        $pdo = new PDO('sqlite:' . $path, null, null, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        $pdo->exec('PRAGMA foreign_keys = ON');
    }
    return $pdo;
}

// Every query sends its values apart from the SQL, as a prepared
// statement. Module 3 explains why this matters.
function query(string $sql, array $params = []): PDOStatement
{
    $statement = db()->prepare($sql);
    $statement->execute($params);
    return $statement;
}

function fetch_one(string $sql, array $params = []): ?array
{
    $row = query($sql, $params)->fetch();
    return $row === false ? null : $row;
}

function fetch_all(string $sql, array $params = []): array
{
    return query($sql, $params)->fetchAll();
}

db() opens the SQLite file once per request and makes every database error an exception, so a failure stops the request rather than carrying on with bad data. It refuses to create an empty database by accident. The other three functions are the only way the shop queries the database. The SQL is written with a ? placeholder for each value, and the values travel separately in $params. That is a prepared statement, and Module 3 explains why it keeps a value from ever changing the query.

src/helpers.php: printing pages

<?php
declare(strict_types=1);

// Encodes a value for HTML text or a quoted attribute. Every value a
// page prints goes through e(). Module 3 explains why.
function e(string|int|float|null $value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE,
        'UTF-8');
}

// Money is held in cents and shown as R1,250.00.
function money(int $cents): string
{
    return sprintf('R%s.%02d', number_format(intdiv($cents, 100)),
        $cents % 100);
}

// Sends a whole page: the layout around the page's own HTML.
function render(string $title, string $body, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: text/html; charset=utf-8');
    $items = array_sum($_SESSION['cart'] ?? []);
    ?>
<!doctype html>
<html lang="en-ZA">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($title) ?> | <?= e(config('shop_name')) ?></title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header class="top">
  <a class="brand" href="/"><?= e(config('shop_name')) ?></a>
  <nav>
    <a href="/?r=catalogue">Products</a>
    <a href="/?r=cart">Cart (<?= e($items) ?>)</a>
  </nav>
</header>
<main>
<?= $body /* the page's own HTML, every value in it already encoded */ ?>
</main>
<footer>A practice copy of an invented shop, for learning only.</footer>
</body>
</html>
<?php
}

// Sends the browser on after a form is sent (Post/Redirect/Get).
function redirect(string $location): never
{
    header('Location: ' . $location, true, 303);
    exit;
}

// Shows an error page with the right status code, and stops.
function error_page(int $status, string $message): never
{
    $titles = [400 => 'Bad request', 403 => 'Not allowed',
        404 => 'Not found', 405 => 'Method not allowed'];
    $title = $titles[$status] ?? 'Error';
    render($title, '<h1>' . e($title) . '</h1><p>' . e($message) . '</p>',
        $status);
    exit;
}

e() is the most important function in the file. Every value the shop prints passes through it, so a character that means something in HTML, such as an angle bracket or an apostrophe, is shown as text and never treated as markup. Module 3 explains this in full. money() shows whole cents as rands without ever using a fraction, so R1,250.00 is always exactly right. render() wraps each page in the shared layout. It prints $body as it is, because the page built that HTML itself with every value already encoded. redirect() sends the browser on after a form with status 303, so reloading the next page never sends the form again. error_page() gives each refusal its proper status code.

src/security.php: the session and the form token

<?php
declare(strict_types=1);

// A security baseline. Module 2 adds the sign-in rules for sessions,
// and Module 4 completes the form token and adds the security headers.

// Starts the session with sound cookie settings (Module 2 explains them).
function start_session(): void
{
    session_start([
        'name'            => 'tbo_session',
        'use_strict_mode' => true,
        'cookie_httponly' => true,
        'cookie_samesite' => 'Lax',
        'cookie_secure'   => is_https(),
    ]);
}

function is_https(): bool
{
    return !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
}

// The form token: a random value tied to this visitor's session and
// sent with every form that changes something (Module 4 explains it).
function form_token(): string
{
    $_SESSION['form_token'] ??= bin2hex(random_bytes(32));
    return $_SESSION['form_token'];
}

function token_field(): string
{
    return '<input type="hidden" name="token" value="'
        . e(form_token()) . '">';
}

// Refuses a form whose token is missing or wrong.
function check_form_token(): void
{
    $sent = $_POST['token'] ?? '';
    if (!is_string($sent) || !hash_equals(form_token(), $sent)) {
        error_page(403, 'This form has expired. Reload the page and try again.');
    }
}

A session is how the shop recognises the same visitor from one request to the next: PHP gives the browser a cookie holding a long random session id and keeps the visitor's data, such as the cart, on the server under that id. start_session() sets the cookie so that scripts in the page cannot read it, the browser does not send it with forms posted from other sites, and, on a live site over HTTPS, it travels only over HTTPS. Strict mode makes PHP refuse a session id it did not create itself. Module 2 explains each setting.

The form token is a random value tied to the visitor's session. Every form that changes something carries it in a hidden field, and the server refuses the form with 403 unless the token matches. It means the request came from the shop's own page. Module 4 explains it, completes it with a second check and puts it on every form.

public/index.php: the front controller and router

<?php
declare(strict_types=1);

// The front controller: every request to the shop starts here.
// Only this folder, public/, is served. The code lives in src/.

$src = dirname(__DIR__) . '/src';
require $src . '/config.php';
require $src . '/db.php';
require $src . '/helpers.php';
require $src . '/security.php';
require $src . '/pages/catalogue.php';
require $src . '/pages/product.php';
require $src . '/pages/cart.php';

// The routes: ?r=name, and the function that answers each method.
// Every route that changes something is POST.
$routes = [
    'catalogue' => ['GET' => 'catalogue_page'],
    'product'   => ['GET' => 'product_page'],
    'cart'      => ['GET' => 'cart_page', 'POST' => 'cart_post'],
];

start_session();

$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$route = $_GET['r'] ?? 'catalogue';
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if (!in_array($path, ['/', '/index.php'], true)
    || !is_string($route) || !isset($routes[$route])) {
    error_page(404, 'We could not find that page.');
}
if (!isset($routes[$route][$method])) {
    header('Allow: ' . implode(', ', array_keys($routes[$route])));
    error_page(405, 'That page does not accept this kind of request.');
}
$routes[$route][$method]();

This is the only PHP file in the web root, and every page request passes through it. It loads the code from src/, starts the session, and looks up the route named in the address (?r=product) in a fixed table. Only a function listed in the table can ever run. An address it does not know gets 404, and a known route asked for in a way it does not accept, such as a POST to the catalogue, gets 405. Every route that changes something accepts only POST, so following a link or loading a page can never change the cart. Later modules add their routes to the table, one line each.

src/pages/catalogue.php: the product list

<?php
declare(strict_types=1);

// The product list: the shop's home page.
function catalogue_page(): void
{
    $products = fetch_all(
        'SELECT id, name, price_cents, supplier FROM products ORDER BY name'
    );
    ob_start();
    ?>
<h1>Homeware from South African makers</h1>
<ul class="products">
<?php foreach ($products as $product): ?>
  <li>
    <a href="/?r=product&amp;id=<?= e($product['id']) ?>">
      <?= e($product['name']) ?></a>
    <span class="maker"><?= e($product['supplier']) ?></span>
    <span class="price"><?= e(money($product['price_cents'])) ?></span>
  </li>
<?php endforeach ?>
</ul>
<?php
    render('Products', ob_get_clean());
}

src/pages/product.php: one product

<?php
declare(strict_types=1);

// One product, found by its id. An id that is not a product gets 404.
function product_page(): void
{
    $id = filter_var($_GET['id'] ?? '', FILTER_VALIDATE_INT,
        ['options' => ['min_range' => 1]]);
    $product = $id === false ? null : fetch_one(
        'SELECT id, name, description, price_cents, supplier
         FROM products WHERE id = ?',
        [$id]
    );
    if ($product === null) {
        error_page(404, 'We could not find that product.');
    }
    ob_start();
    ?>
<h1><?= e($product['name']) ?></h1>
<?php if ($product['supplier'] !== null): ?>
<p class="maker">Made by <?= e($product['supplier']) ?></p>
<?php endif ?>
<p class="price"><?= e(money($product['price_cents'])) ?></p>
<p><?= e($product['description']) ?></p>
<form method="post" action="/?r=cart">
  <?= token_field() ?>
  <input type="hidden" name="action" value="add">
  <input type="hidden" name="product_id" value="<?= e($product['id']) ?>">
  <button type="submit">Add to cart</button>
</form>
<?php
    render($product['name'], ob_get_clean());
}

The product page accepts an id only if it is a whole number of 1 or more. Anything else, or an id that is not a product, gets the 404 page. The "Add to cart" form is sent by POST and carries the form token.

src/pages/cart.php: the cart in the session

<?php
declare(strict_types=1);

// The cart lives in the session as [product id => quantity].
// Prices always come from the database, never from the browser.

const MAX_PER_LINE = 20;

function cart_page(): void
{
    $lines = [];
    $total = 0;
    foreach ($_SESSION['cart'] ?? [] as $id => $qty) {
        $product = fetch_one(
            'SELECT id, name, price_cents FROM products WHERE id = ?', [$id]);
        if ($product === null) {
            unset($_SESSION['cart'][$id]);   // the product has gone
            continue;
        }
        $amount = $product['price_cents'] * $qty;
        $total += $amount;
        $lines[] = $product + ['qty' => $qty, 'amount' => $amount];
    }
    ob_start();
    ?>
<h1>Your cart</h1>
<?php if ($lines === []): ?>
<p>Your cart is empty. <a href="/">See our products</a>.</p>
<?php else: ?>
<table class="cart">
  <tr><th>Product</th><th>Quantity</th><th>Amount</th><th>Remove</th></tr>
<?php foreach ($lines as $line): ?>
  <tr>
    <td><?= e($line['name']) ?></td>
    <td><?= e($line['qty']) ?></td>
    <td><?= e(money($line['amount'])) ?></td>
    <td><form method="post" action="/?r=cart">
      <?= token_field() ?>
      <input type="hidden" name="action" value="remove">
      <input type="hidden" name="product_id" value="<?= e($line['id']) ?>">
      <button type="submit">Remove</button></form></td>
  </tr>
<?php endforeach ?>
  <tr><th colspan="2">Total</th><td><?= e(money($total)) ?></td><td></td></tr>
</table>
<?php endif ?>
<?php
    render('Your cart', ob_get_clean());
}

// Adds one of a product to the cart, or removes a line, then shows it.
function cart_post(): void
{
    check_form_token();
    $id = filter_var($_POST['product_id'] ?? '', FILTER_VALIDATE_INT,
        ['options' => ['min_range' => 1]]);
    $action = $_POST['action'] ?? '';
    if ($id === false || !in_array($action, ['add', 'remove'], true)) {
        error_page(400, 'We could not understand that request.');
    }
    if ($action === 'add') {
        if (fetch_one('SELECT id FROM products WHERE id = ?', [$id]) === null) {
            error_page(404, 'We could not find that product.');
        }
        $qty = ($_SESSION['cart'][$id] ?? 0) + 1;
        $_SESSION['cart'][$id] = min($qty, MAX_PER_LINE);
    } else {
        unset($_SESSION['cart'][$id]);
    }
    redirect('/?r=cart');
}

The cart holds only product ids and quantities. Every name and price comes from the database each time the cart is shown, so nothing a browser sends can change what something costs. Adding checks the token, the product and the action, adds one item, and keeps any line to 20 at most. Module 3 adds a quantity field with its own validation, and Module 5 turns the cart into an order.

public/style.css: the look

/* The practice shop's look. It has no inline styles or scripts. */
body { margin: 0; font: 17px/1.5 system-ui, sans-serif; color: #18222f; }
.top { display: flex; justify-content: space-between; align-items: center;
  padding: 0.8rem 1.2rem; background: #163a5f; }
.top a { color: #fff; text-decoration: none; margin-left: 1rem; }
.top .brand { margin-left: 0; font-weight: bold; }
main { max-width: 48rem; margin: 0 auto; padding: 1rem 1.2rem; }
.products { list-style: none; padding: 0; display: grid; gap: 0.8rem;
  grid-template-columns: repeat(auto-fill, minmax(13rem, 1fr)); }
.products li { border: 1px solid #d5dce4; padding: 0.8rem; }
.maker { display: block; color: #566273; font-size: 0.9rem; }
.price { display: block; font-weight: bold; }
.cart { border-collapse: collapse; width: 100%; }
.cart th, .cart td { border-bottom: 1px solid #d5dce4; padding: 0.4rem;
  text-align: left; }
button { font: inherit; padding: 0.4rem 0.9rem; }
footer { text-align: center; color: #566273; font-size: 0.85rem;
  padding: 2rem 1rem; }

The shop's look is kept in this one file, with no styles or scripts written inside the pages. That makes Module 4's Content-Security-Policy simple to apply.

migrations/000_products.sql: the products table

-- Module 0: the products the shop sells.
-- Money is held in whole cents, never as a decimal.
CREATE TABLE products (
    id          INTEGER PRIMARY KEY,
    name        TEXT NOT NULL,
    slug        TEXT NOT NULL UNIQUE,
    description TEXT NOT NULL,
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    image_name  TEXT,
    stock       INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0),
    supplier    TEXT
);

Money is held as whole cents, so R285.00 is stored as 28500 and no rounding ever creeps in. The table has no column for anything to do with cards, and no table in the shop ever will: card details stay on the payment provider's page (Module 5).

tools/setup.php: the database and its sample data

<?php
declare(strict_types=1);

// Creates the shop's database and its sample data. From the shop folder:
//   php tools/setup.php           applies any migrations not yet applied
//   php tools/setup.php --reset   deletes the database and starts again

require dirname(__DIR__) . '/src/config.php';
require dirname(__DIR__) . '/src/db.php';

// The sample data for each migration. Later modules add theirs here.
$seeds = [
    '000_products.sql' => 'seed_products',
];

function seed_products(): void
{
    $products = [
        ['Stoneware Mug', 'stoneware-mug', 28500, 24, 'Saltpan Ceramics',
            'A hand-thrown 350 ml mug in a speckled oatmeal glaze.'],
        ['Serving Bowl', 'serving-bowl', 64000, 8, 'Saltpan Ceramics',
            'A wide stoneware bowl, 28 cm across, glazed deep blue inside.'],
        ['Linen Apron', 'linen-apron', 42000, 12, 'Dwarsrivier Linen',
            'A full-length apron in washed linen with two deep pockets.'],
        ['Table Runner', 'table-runner', 56000, 10, 'Dwarsrivier Linen',
            'A two-metre runner in natural linen with a hand-stitched hem.'],
        ["Ouma's Rusk Tin", 'oumas-rusk-tin', 19500, 15, null,
            'A printed tin with a tight lid that keeps rusks crisp.'],
    ];
    foreach ($products as [$name, $slug, $cents, $stock, $maker, $about]) {
        query('INSERT INTO products
               (name, slug, price_cents, stock, supplier, description)
               VALUES (?, ?, ?, ?, ?, ?)',
            [$name, $slug, $cents, $stock, $maker, $about]);
    }
}

$path = config('db_path');
if (in_array('--reset', $argv, true) && is_file($path)) {
    unlink($path);
    echo 'Deleted the old database.', PHP_EOL;
}
if (!is_dir(dirname($path))) {
    mkdir(dirname($path), 0750, true);
}
touch($path);

query('CREATE TABLE IF NOT EXISTS migrations
       (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)');
$files = glob(dirname(__DIR__) . '/migrations/*.sql');
sort($files);
foreach ($files as $file) {
    $name = basename($file);
    if (fetch_one('SELECT name FROM migrations WHERE name = ?', [$name])) {
        continue;
    }
    db()->beginTransaction();
    db()->exec(file_get_contents($file));
    if (isset($seeds[$name])) {
        $seeds[$name]();
    }
    query('INSERT INTO migrations (name, applied_at) VALUES (?, ?)',
        [$name, date('c')]);
    db()->commit();
    echo 'Applied ', $name, PHP_EOL;
}
echo 'The database is ready: ', $path, PHP_EOL;

The setup script applies each migration file once, in order, and adds its sample data. Run it again after a later module adds a migration and it applies only the new one, keeping what you have made. With --reset it deletes the database and builds it afresh. It inserts the sample products with the same prepared statements as the shop, and it creates the data/ folder with permissions that let only you write to it on Linux and macOS (Windows ignores them, and Module 6 deals with permissions on the live server).

Table 3. The habits already in the skeleton, and where each is explained in full
HabitWhere you see itExplained in
The database and code outside the web rootThe folders, -t public, the router's 404This module, Module 4 and Module 6
Every query a prepared statementquery() with ? placeholdersModule 3
Every printed value encodede() in every pageModule 3
Sound session cookie settingsstart_session()Module 2
A form token on every form that changes somethingtoken_field() and check_form_token()Module 4
Changes only by POST, then a redirectThe route table, redirect()Module 4
Prices only from the databasecart_page()Module 5
Worked example: following one request through the shop

You select Ouma's Rusk Tin in the product list. Here is what happens, step by step, as Figure 3 shows.

  1. The browser asks. It sends GET /?r=product&id=5 to localhost:8000, with the session cookie it was given on the first page.
  2. The server hands over. The address names no file, so PHP's built-in server runs public/index.php, the index file in its web root.
  3. The router decides. index.php loads the code, starts the session (reading the cart from the session id in the cookie), checks that the path is /, and finds product in its table with product_page as the function for GET.
  4. The page checks its input. product_page() reads id and accepts it because 5 is a whole number of at least 1.
  5. The database answers. fetch_one() sends the query with a placeholder, and the 5 separately. SQLite returns one row: Ouma's Rusk Tin, 19500 cents, no maker, its description.
  6. The page is drawn. The template passes every value through e(), so the apostrophe in "Ouma's" is written as &#039;. The form gets the session's token. render() wraps it in the layout, with "Cart (0)" counted from the session.
  7. The response returns. Status 200, Content-Type: text/html; charset=utf-8, and the page. The browser then asks for /style.css, which the server sends straight from public/ without running any PHP.

Now try /?r=product&id=999. Steps 1 to 4 are the same, but in step 5 SQLite returns no row, so product_page() calls error_page(404, ...) and the browser gets the "Not found" page with status 404. Try /?r=product&id=abc and step 4 refuses it before the database is ever asked.

Browser GET /?r=product &id=5 PHP server -t public runs index.php index.php session, path, route table product_page() id checked, query with ? Database data/ shop.sqlite 1 2 3 4 5 the row 6 render() puts every value through e() 7 the page, 200 No such product: a 404 page
Figure 3. One request's path through the shop, and back. Every request for a page passes through index.php, and every value on the way out passes through e().

5. Seed it and run it

In a terminal, go into the shop folder and create the database:

cd practice-shop
php tools/setup.php

You should see:

Applied 000_products.sql
The database is ready: /home/you/practice-shop/data/shop.sqlite

The path is wherever your folder is, such as C:\Users\you\Documents\practice-shop\data/shop.sqlite on Windows. Now start the shop, from the same folder:

php -S localhost:8000 -t public

The server prints a line such as PHP 8.5.12 Development Server (http://localhost:8000) started and then one line for each request it answers. Leave this terminal open: the shop runs for as long as it does, and Ctrl+C stops it. Open http://localhost:8000 in your browser. You should see five products: Linen Apron, Ouma's Rusk Tin, Serving Bowl, Stoneware Mug and Table Runner, in that order, each with its maker and price, except the rusk tin, which has no maker recorded.

Table 4. If it does not work
What you seeWhat it meansWhat to do
could not find driverPHP's SQLite extension is not loaded.On Windows, edit the two lines in php.ini as section 2 says. On Linux, install php-sqlite3 (or php8.5-sqlite3). Check with php -m.
Failed to listen on localhost:8000 (reason: Address already in use)Something, often another copy of the server, is already using port 8000.Stop the other copy with Ctrl+C, or use another port: php -S localhost:8080 -t public, and later php tools/checks.php http://localhost:8080.
A plain "Not Found" page saying the requested resource / was not foundYou started the server without -t public, or in the wrong folder.Stop it at once with Ctrl+C. Without -t public the server would hand out the whole shop folder, the database file included. Start it again from practice-shop with -t public.
Directory public does not exist.You are not in the practice-shop folder.Go into it with cd first.
No database. Run: php tools/setup.phpThe setup script has not been run, or was run from another folder.Run it from practice-shop.
Call to undefined function or syntax error, with a file and lineA typing slip in that file, or a missing require line.Compare that file, at and just before the line named, with its listing.
A blank pageAn error that PHP was set not to display.Read the terminal where the server runs: the error is there.

6. Look inside with the developer tools

A tour of the shop

Before you open the developer tools, walk round the shop as a customer would, and notice what is there and what is not yet.

  • The product list is the home page, at / or /?r=catalogue. Each product links to its own page.
  • A product page, such as /?r=product&id=5, shows the name, the maker when there is one, the price, the description and an "Add to cart" button.
  • The cart, at /?r=cart, lists each product with its quantity and amount, a Remove button on each line, and the total. Each press of "Add to cart" adds one, up to 20 of a product. The header shows how many items are in it.
  • The refusals: /?r=product&id=999 and /?r=nothing give the shop's "Not found" page. These are part of the shop too.

What is missing is what the later modules build: accounts and sign-in (Module 2), search, quantities and product pictures (Module 3), the security headers (Module 4), checkout and payment (Module 5) and the staff pages (Modules 2, 3, 5 and 7). None of that is a weakness in the skeleton. It is simply not built yet, and nothing in the skeleton depends on it.

The Network tab

Open the developer tools on the product list and select Network. Turn on Persist Logs in Firefox (in the Network tab's settings) or tick Preserve log in Chrome and Edge, so that the list is kept when a form sends you to another page. Then reload. Each request is a row:

  • Method: GET for loading a page, POST for sending a form. Chrome and Edge hide this column at first: right-click the column headings and tick Method.
  • The address (File or Name): /, style.css and so on.
  • Status: 200 for a page that was found, 303 for a redirect after a form, 404 for not found, 403 for refused.
  • Type: html for the page, css for the stylesheet.

Select the first row. The Headers section shows the request your browser sent, including its Cookie header once it has one, and the response headers the shop sent back. The Response section shows the HTML as it arrived. You may also see a request for /favicon.ico answered with 404: browsers ask every site for an icon, and the shop has none. That is expected.

Now open a product and press "Add to cart". Two new rows appear: a POST to /?r=cart with status 303 and a Location: /?r=cart response header, and then the browser's GET for the cart with status 200. That pair is the Post/Redirect/Get pattern from redirect().

View the page source

Right-click the page and choose View Page Source, or press Ctrl+U (Cmd+Option+U in Chrome on a Mac, Cmd+U in Firefox on a Mac). This shows the HTML exactly as the shop sent it, before the browser drew it. On the rusk tin's page, find the heading. The page shows "Ouma's Rusk Tin", but the source says <h1>Ouma&#039;s Rusk Tin</h1>. That &#039; is e() at work: the apostrophe was sent as a character reference, which the browser shows as text and can never mistake for part of the markup.

The session cookie

Select Storage in Firefox or Application in Chrome and Edge, then Cookies and http://localhost:8000. You will see one cookie, tbo_session. In the Network tab, the very first response the shop sent you carried it in a Set-Cookie header, and every request since has sent it back in a Cookie header.

Worked example: reading the session cookie's settings

The first response's header was:

Set-Cookie: tbo_session=6061e4bbff6ee95923b4d944a9af7183; path=/; HttpOnly; SameSite=Lax

The cookie table shows the same, column by column. Here is what each part tells you, in a sentence each. Module 2 goes into each in depth.

  • Name, tbo_session. The name start_session() gave it, rather than PHP's default, PHPSESSID, which tells anyone the shop runs on PHP. That hides little, but there is no reason to announce it.
  • Value. The session id: a long random string that is the visitor's key to their session. Whoever holds it is, to the shop, that visitor, which is why every other setting protects it.
  • Domain localhost, Path /. The browser sends it to this site only, for every page.
  • Expires: Session. No expiry date was set, so the browser forgets it when it closes.
  • HttpOnly: yes. Scripts running in the page cannot read it, so a script that should never have been there could not take it.
  • Secure: no. The shop runs over plain HTTP on your own computer, so is_https() is false. On the live shop, over HTTPS, it becomes yes, and the cookie then never travels unencrypted (Module 6).
  • SameSite: Lax. The browser leaves it out of forms posted to the shop from other sites, which is one of the defences against forged requests (Module 4).

One protection does not show in the cookie at all: strict mode. If a browser sends a session id the shop never issued, PHP ignores it and issues a new one, so nobody can choose a visitor's session id for them in advance.

Your baseline

A baseline is a record of how something is now, made before you change it, so that later you can show exactly what changed. In the practical work you record the shop's baseline: for each request, its method, address, status and the response headers that matter, the session cookie's settings, and what the shop does not send yet. One row of it looks like this:

Table 5. One row of a baseline
RequestStatusResponse headers that matter
POST /?r=cart (Add to cart)303Location: /?r=cart, X-Powered-By: PHP/8.5.12, PHP's three session cache headers. No security headers.

Two things in it are worth noticing now. X-Powered-By tells anyone who asks which PHP version runs the shop, which Module 6 switches off on the live server. And there are no security headers at all, the headers that tell a browser to switch on its own protections. Module 4 adds them, and you will compare its result with this baseline.

7. Your first checks

Looking at pages by hand is a good start, but it is slow, and it is easy to forget to look again after a change. So the shop has a script that checks it for you. Each check states what a working control does and confirms it against your running shop. If someone later breaks a control by accident, its check fails.

tools/checks.php

<?php
declare(strict_types=1);

// Checks that your shop's controls work, by sending it requests.
// Start the shop first, then run from the shop folder:
//   php tools/checks.php
// Each module adds its own checks near the end of this file.

// A small browser: it sends requests to your shop and keeps its cookies.
final class Browser
{
    private array $cookies = [];

    public function __construct(private string $base)
    {
    }

    public function get(string $path): array
    {
        return $this->send('GET', $path, '');
    }

    public function post(string $path, array $form): array
    {
        return $this->send('POST', $path, http_build_query($form));
    }

    // Returns the status code, the headers (name => values) and the body.
    private function send(string $method, string $path, string $data): array
    {
        $headers = ['Content-Type: application/x-www-form-urlencoded'];
        if ($this->cookies !== []) {
            $headers[] = 'Cookie: ' . http_build_query($this->cookies, '', '; ');
        }
        $context = stream_context_create(['http' => [
            'method'          => $method,
            'header'          => implode("\r\n", $headers),
            'content'         => $data,
            'ignore_errors'   => true,   // read 4xx and 5xx pages too
            'follow_location' => 0,      // see each response as it is
        ]]);
        $html = @file_get_contents($this->base . $path, false, $context);
        $lines = http_get_last_response_headers();
        if ($html === false || $lines === null) {
            fwrite(STDERR, "Is the shop running at $this->base?\n");
            exit(2);
        }
        $found = [];
        foreach (array_slice($lines, 1) as $line) {
            [$name, $value] = explode(':', $line, 2) + [1 => ''];
            $found[strtolower(trim($name))][] = trim($value);
        }
        foreach ($found['set-cookie'] ?? [] as $cookie) {
            [$name, $value] = explode('=', explode(';', $cookie)[0], 2);
            $this->cookies[$name] = $value;
        }
        $status = (int) explode(' ', $lines[0])[1];
        return ['status' => $status, 'headers' => $found, 'body' => $html];
    }
}

// Prints PASS or FAIL for one check, and returns 1 if it failed.
function check(string $name, bool $passed): int
{
    echo $passed ? 'PASS  ' : 'FAIL  ', $name, PHP_EOL;
    return $passed ? 0 : 1;
}

// Finds the form token in a page, to send it back as a browser would.
function token_in(string $html): string
{
    preg_match('/name="token" value="([0-9a-f]+)"/', $html, $match);
    return $match[1] ?? '';
}

$browser = new Browser($argv[1] ?? 'http://localhost:8000');
$failed = 0;

// Module 0: the skeleton works.
$page = $browser->get('/?r=catalogue');
$names = ['Stoneware Mug', 'Serving Bowl', 'Linen Apron', 'Table Runner',
    "Ouma's Rusk Tin"];
$listed = array_filter($names, fn ($name) =>
    str_contains($page['body'], htmlspecialchars($name, ENT_QUOTES)));
$failed += check('the catalogue returns 200 and lists the sample products',
    $page['status'] === 200 && count($listed) === count($names));

$failed += check('an unknown product returns 404',
    $browser->get('/?r=product&id=999999')['status'] === 404);

$product = $browser->get('/?r=product&id=1');
$browser->post('/?r=cart', ['token' => token_in($product['body']),
    'action' => 'add', 'product_id' => '1']);
$failed += check('an item added to the cart is still there on the next request',
    str_contains($browser->get('/?r=cart')['body'], 'Stoneware Mug'));

// Each later module adds its checks above this line.
echo $failed === 0 ? 'All checks passed.' : "$failed check(s) failed.", PHP_EOL;
exit($failed === 0 ? 0 : 1);

The Browser class is a very small browser: it sends a request to your shop, keeps the cookies the shop sets and sends them back next time, just as your real browser does. It never follows redirects, so a check can see a 303 for what it is. check() prints PASS or FAIL. token_in() finds the form token in a page, so that a check can send a form the way a browser would after loading the page. A new Browser is a new visitor with an empty cart.

The three checks are Module 0's:

  1. The catalogue returns 200 and lists the sample products. It looks for each name as the shop would encode it, so it finds "Ouma's Rusk Tin" in its encoded form.
  2. An unknown product returns 404.
  3. An item added to the cart is still there on the next request, which shows that the session, the cookie and the form token work together.

With the shop running in one terminal, open a second terminal in practice-shop and run:

php tools/checks.php
PASS  the catalogue returns 200 and lists the sample products
PASS  an unknown product returns 404
PASS  an item added to the cart is still there on the next request
All checks passed.

If the shop is not running, the script says Is the shop running at http://localhost:8000? and stops. Every module from now on adds checks for its own controls, above the line that says so, and you run the whole file after every change. By Module 8 it holds a check for every control the shop has, and Module 8 shows how to prove that each check can fail when its control is missing.

Tip

Keep a notes file for the course, such as practice-shop/notes.md, and paste each module's check output and your baseline into it. It is outside public/, so the shop never serves it, and by Module 8 it is the evidence for your launch review.

Sources

  • Cybercrimes Act 19 of 2020, section 2 (unlawful access).
  • PHP, Supported Versions: https://www.php.net/supported-versions.php (read on 10 November 2026)
  • PHP, Downloads and installation instructions: https://www.php.net/downloads.php (read on 10 November 2026)
  • PHP, release announcements for PHP 8.5.12 and 8.4.27, 21 October 2026: https://www.php.net/ (read on 10 November 2026)
  • PHP Manual, Built-in web server: https://www.php.net/manual/en/features.commandline.webserver.php
  • PHP Manual, SQLite functions for PDO (PDO_SQLITE): https://www.php.net/manual/en/ref.pdo-sqlite.php
  • PHP Manual, http_get_last_response_headers: https://www.php.net/manual/en/function.http-get-last-response-headers.php
  • Ubuntu packages, php in Ubuntu 24.04 (noble) and 26.04 (resolute): https://packages.ubuntu.com/ (read on 10 November 2026)
  • Debian packages, php in Debian 13 (trixie): https://packages.debian.org/ (read on 10 November 2026)
  • Chrome for Developers, Inspect network activity: https://developer.chrome.com/docs/devtools/network
  • Chrome for Developers, View, add, edit, and delete cookies: https://developer.chrome.com/docs/devtools/application/cookies
  • Firefox Source Docs, Network Monitor: https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/index.html
  • MDN Web Docs, Set-Cookie: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie