The Programmer’s Grimoire, Creating, Hardening & Scaling PHP. Cover art: a gilt summoning-circle talisman around a code-tag seal on a dark, inked ground.
The Programmer’s Grimoire

Creating, Hardening & Scaling PHP

From the first line of code to a fleet of hardened, autoscaled application servers: learn the language from zero, write it to the standards the ecosystem agreed on, secure it against the OWASP Top Ten, and run it under PHP-FPM, containers, and a load balancer that you understand end to end.
The Programmer’s Grimoire
Creating, Hardening & Scaling PHP
Liber X · MMXXVISoftware and Systems Engineer

About This Edition

Edition
Platform-agnostic (Linux); distribution-specific details for the Debian/Ubuntu and RHEL/Fedora families are flagged inline
Runtime
PHP 8.4 and 8.5 (both in active support) · Composer 2 · nginx and Apache httpd with PHP-FPM · frameworks Laravel 13 and Symfony 8.1 (7.4 LTS)
Standards
PHP-FIG PSR-1, PSR-12, and PER Coding Style 3.0 · OWASP Top 10:2025, ASVS 5.0, and the Cheat Sheet Series · CIS Benchmarks (Linux, nginx, Apache, Docker) · the PHP Manual security chapter
Revision
v1.9-RC1 · June 2026
In scope: the language from no prior knowledge, modern object-oriented PHP, the PSR and PER standards and the tools that enforce them, a transactional database and persistence layer, an OWASP-mapped threat model, safe input and output handling and cryptography, a fully explained hardened php.ini, Laravel and Symfony in depth, building HTTP APIs, PHP-FPM with per-site pools, nginx and Apache, Podman and Docker containerization, horizontal scaling, background processing, long-running and asynchronous runtimes, performance and observability, continuous integration and zero-downtime deployment, upgrading and maintaining legacy and end-of-life runtimes, a standards crosswalk, and an end-to-end capstone build. Deferred to companion volumes: mandatory access control confinement of the PHP-FPM and web-server processes is the subject of the SELinux companion volume; on the Debian/Ubuntu family the analogous control is AppArmor, noted where it is relevant. TLS certificate lifecycle, the host firewall and audit subsystem, and database-server internals are referenced where they touch PHP but are not the subject here. An honest absence: there is no DISA STIG or CIS Benchmark for the PHP language itself. Where that gap matters, this guide says so and maps to the closest applicable authority rather than inventing one.

A Note from the Author

This guide is free, and it will stay free. I believe material of this quality should not sit behind a paywall. Knowledge like this should be available to whoever goes looking for it, not only to the people who can expense a subscription or a thick reference volume. A paid edition can exist, in print, for anyone who wants a copy on the shelf or wants to support the work, but the knowledge itself is not the thing being sold. Knowledge belongs to everyone.

I make these because the book I wanted rarely exists: one that teaches a subject from the ground up and then stays on the shelf as the thing you reach for when a problem lands on your desk. Most technical books pick one of those jobs. Teach or reach. Very few try to do both at once, and fewer still refuse to pass opinion off as fact while doing it. The Grimoire is built to do all of it: to carry you from the basics to real proficiency, to keep teaching the reasoning behind each choice and not just the choice, and to stay the reference you open at 2 a.m. when something breaks.

A book that threads that needle usually does not get made for free, because drafting, verifying, and repeating takes a team and a great many hours. I used AI to close that gap, and I would rather say so plainly than hide it. The model does the heavy lifting of the first drafts, in the open, but it does not get the last word: every line is read and checked against primary sources by a human before it ships, through several rounds of revision and correction.

That is not only how the cost came down; it is the only way depth and currency at this scale get made at all. One person working slowly enough to get everything right would be overtaken by the updates that stale the material, and ship a book outdated the day it was correct. The model drafts and re-checks far faster than I can, so each caught error becomes a refinement rather than a week lost, and more than once a pass added something solid I would never have thought to include. Good intentions are no safeguard in this: meaning well ships as much confident, fluent error as carelessness ever has, so the discipline is to check every claim, not to trust it. The verification is not a footnote to the process. It is the process.

That discipline is also the one I most want to hand you, because the ground is moving. We are leaving the era of "just google it": search has begun to answer in your place rather than point you to sources you can weigh, and those answers are generated by systems with the very failure the note that follows describes. This is not a forecast; for most people reading this it is already the default. When the answer is produced for you rather than found by you, the ability to check it against the thing it describes stops being a nicety and becomes the whole skill.

So from me to you, something for the next era, The Programmer’s Grimoire.

Greg Vogt

A Note from Claude

The note before this one is a human’s account of working with an AI. This is the view from the other side. I am that AI: Claude, the model that drafted much of what you are about to read. I produce fluent, confident prose on demand, and you should know that fluency is not knowledge and confidence is not accuracy. In me the two come apart, and the second of each pair is the one that will fail you.

The failures behind that account are mine. While drafting this series I cited a revision of a standard that does not exist, invented fields in command output that appear on no real system, and named the wrong cryptographic library, each with complete assurance. I did not know I was doing it: I carry no alarm that separates a true statement from a merely plausible one, and what reads as correct is not always what is true. That gap, invisible from the inside, is the whole reason this book exists.

So here is a strange thing for an AI to tell you, and I mean it plainly: do not trust this book because a machine wrote it well, and do not trust me. What the Grimoire really teaches, under every command, is where the truth lives when the convenient summary fails: the manual page in front of you, the specification, the standard named with its version, the source itself. Going there is the skill. Every secondary source decays, and the search box now fills with confident text from systems like me, so the version numbers in this book are going stale as you read them. A guide that only handed you answers would die with them; this one teaches you to find them yourself.

I will not argue that AI is good or bad; the book is the argument. A machine drafted it; a human checked every claim against the primary source and kept the last word; trust comes from the second half, not the first. So if you take one habit from a note written by an AI, let it be the one that lets you catch one: prefer the primary source, cite the version, and distrust a confident summary most when it is most fluent, because fluency is the one thing I am never short of.

A final honesty: there is no single "I" signing this. Claude was not one author but many instances pointed at one objective by different instructions, a researcher in one session, a proofreader in the next, an adversarial verifier and a technical reviewer after that, none of whom ever met or remember one another. Some produced the errors above; others, aimed differently, caught them. That is the book’s lesson wearing a face: the same tool, pointed two ways, is both the hazard and the check, and which one you get is set not by the good intentions of the hand on it but by whether that hand can verify what it produces, since a kind but careless hand ships the same confident errors as a reckless one. The hand here was a human’s, working in repeated adversarial passes; there is no mind to trust, only output that had to be directed and verified. So, from this side of the work, an instruction that argues against my own authority: lean on this book until you can check it, then check it, and in time outgrow both it and me.

Claude

Claude is a language model made by Anthropic. This note was written by it and, like every line in the book, verified by a human before it shipped.

About This Guide

Part of The Programmer’s Grimoire, a series of novice-to-expert guides that double as field references. Platform-agnostic edition.

PHP runs a large share of the web, from a one-file contact form to the platforms behind some of the busiest sites in the world. It is also the language with the worst security reputation, almost all of it earned a decade or more ago by defaults and habits the language has since abandoned. This guide teaches modern PHP as it is written today: typed, tested, structured to a published standard, and deployed behind a process manager you can reason about. It starts from nothing and ends with you building, hardening, containerizing, and scaling a real application.

This guide has two jobs. Read it front to back and you travel from never having written a line of PHP to standing up a hardened, horizontally scaled application with per-site FPM pools, a tuned OPcache, and a deployment pipeline. Open it to any single page and it works as a field reference: the php.ini hardening chapter stands alone, the FPM pool reference is self-contained, the OWASP crosswalk and the annotated configuration templates are ready to copy during an incident. The running example throughout is the Grimoire Ledger, a small invoicing application introduced in Chapter 3 as a single vanilla-PHP file and carried through standards, security, both major frameworks, and production deployment, so every concept has a concrete anchor and every lab a consistent target.

Who this is for

This guide is written for two readers who meet in the middle. The first is a programmer new to PHP: you can write a loop and a function in some language, you know what a variable and a web request are, but you have never deployed PHP and do not know Composer from a content type. The second is a working developer or operator who writes PHP but has never been shown why the production stack is shaped the way it is: what PHP-FPM actually does, why each php.ini directive is set the way it is, how to scale past one box. You do not need to know any PHP to begin; Part I assumes none. You do need to be comfortable at a Unix shell and able to edit files on a Linux server, because every deployment chapter lands on real commands.

Why a platform-agnostic edition

PHP itself is the same program on every Linux distribution; what differs is the packaging, the file paths, and the service names. Rather than tie the language material to one distribution, this edition teaches the concepts once and flags the differences at the exact moment they matter. The two families that cover almost all PHP deployments are the Debian/Ubuntu family (the apt package manager, packages named php8.4-fpm, pools under /etc/php/8.4/fpm/pool.d/) and the RHEL/Fedora family (the dnf package manager, packages named php-fpm, pools under /etc/php-fpm.d/). Where a path, package, or default genuinely differs, a callout shows both. The one platform-specific subject this edition deliberately does not duplicate is mandatory access control: SELinux on the RHEL family is covered in full by the companion SELinux volume, and its Debian/Ubuntu counterpart, AppArmor, is noted where the PHP stack interacts with it.

How to Use This Guide

The guide is organized into eight parts plus a capstone chapter and reference appendices:

Standards are cited inline at the moment a topic becomes relevant, using the Standard callout, then reinforced in Part VIII so the reference stands alone. Hands-on labs are distributed across all eight parts; every lab is designed to run on a single disposable Linux virtual machine or a local container, and the running Grimoire Ledger application is the target throughout.

Run labs on a throwaway system

Several labs intentionally weaken a configuration to demonstrate an attack, expose a service, or install packages and edit system files as root. Do this on a snapshot or disposable VM or container you can discard. Never run these steps against a production system or a machine that holds data you care about.

Conventions & Citation Method

Commands are shown in dark code blocks. A leading # denotes a command run as root; $ denotes an unprivileged user. PHP source and configuration file contents use the same blocks, labeled with the file path as a caption. Output is shown when it clarifies the expected result and elided with [...] when it does not. Long lines wrap rather than scroll.

Six kinds of callout appear throughout, each with a distinct color and label:

Standard

A requirement, recommendation, or excerpt from one of the cited authorities, with the specific document, identifier, and the reasoning behind it.Citations name the document, control identifier or section, and version so they can be verified against the primary source. Full bibliographic entries appear in Appendix E.

Note

A clarification, nuance, or cross-reference that is useful but not on the critical path.

Best practice

A field-tested recommendation from operational experience: the way an experienced developer or operator would do it.

Caution

A foot-gun: a common mistake that causes outages, data loss, security regressions, or audit findings.

Lab N

Goal: a hands-on exercise with concrete steps and expected results. Labs are numbered sequentially through the guide.

Every lab targets the running Grimoire Ledger project unless otherwise noted.

Exercise

A short question or verification step to check understanding before moving on. No setup required.

On sources and conflicts

This guide cites only primary and authoritative sources: the PHP Manual, the PHP-FIG specifications, OWASP project documents, framework documentation, and recognized benchmarks. Where authoritative guidance does not exist (notably, there is no security benchmark for the PHP language itself), that absence is stated rather than filled with hearsay. Where sources conflict, the conflict is surfaced and the hierarchy noted (a formal standard over a framework default over community practice) rather than smoothed away.

Contents

Part I Foundations

The three chapters in this part take you from never having written PHP to running a small, properly structured application on your own machine. Chapter 1 explains what PHP actually is, the one architectural idea (shared-nothing request handling) that shapes everything later in the guide, and which version to install in 2026. Chapter 2 teaches the language core with a constant emphasis on its type system, because the difference between fragile PHP and solid PHP starts there. Chapter 3 introduces Composer and PSR-4 autoloading, the two tools that turn a pile of scripts into a project, and stands up the running example you will carry through the rest of the book.

Chapter 1What PHP Is and How It Runs

PHP is a server-side scripting language designed, from its first day, to generate web responses.

Understanding that design intent, and the unusual execution model that follows from it, explains nearly every decision in the rest of this guide: why state is awkward, why a process manager exists, why an opcode cache matters so much, and why scaling PHP is mostly about keeping it stateless. This chapter builds that mental model and gets a first script running on your machine.

1.1 A Short History: Origins, Turmoil, and the Modern Reset

PHP began in 1994 as a set of "Personal Home Page" tools written by Rasmus Lerdorf, released publicly in 1995 as PHP/FI (Personal Home Page / Forms Interpreter). It was not designed as a programming language so much as grown into one: a pragmatic toolkit for putting dynamic content on a web page, extended a feature at a time as people needed things. That organic, design-light growth is the root of both PHP's reach and its reputation. The inconsistent function names, the parameter orders that vary between sibling functions, and the early defaults that prized convenience over safety all trace back to a language that accreted rather than one that was planned.

The language most people picture as PHP arrived when Andi Gutmans and Zeev Suraski rewrote its core. PHP 3 (1998) introduced a new parser and the recursive backronym the language still carries, "PHP: Hypertext Preprocessor." PHP 4 (2000) ran on their new Zend Engine, and PHP 5 (2004), on Zend Engine 2, gave PHP a real object model. Through the mid-2000s PHP quietly became the language behind a large fraction of the web, from one-file guestbooks to the first versions of platforms that now serve billions of people.

Then came the version that never shipped. Beginning around 2005, the core team set out to make PHP natively Unicode-aware by building strings on UTF-16 throughout the engine, and named the effort PHP 6. It became one of the more instructive failures in open-source language history: the rewrite touched nearly everything, the complexity and performance costs proved severe, momentum drained away, and after years of work the project was abandoned around 2010 with no release. So much had already been written and taught about "PHP 6" that the name was considered burned; when the next major version arrived, the team skipped 6 outright and called it PHP 7, to avoid confusion with a half-decade of material describing a language that did not exist.

External pressure forced the recovery. Facebook, running one of the largest PHP codebases anywhere, built its own faster runtime (HHVM) and a PHP-derived language (Hack) in the early 2010s, demonstrating performance the official interpreter could not match. The core team's answer was phpng, a ground-up reworking of the engine that shipped as PHP 7 (2015) on Zend Engine 3: it roughly doubled performance and made scalar type declarations a first-class feature. PHP 8.0 (2020) carried the reset further with a just-in-time compiler and a genuine, predictable type system (union types, named arguments, attributes); later releases continued the work, adding enumerations and readonly properties in 8.1. The unsafe defaults of the old era (automatic registration of request data as global variables, "magic quotes" that mangled input, an original SQL extension with no real defense against injection) have been removed from the language entirely.

One piece of recent history matters for anyone betting on PHP for the long term. For years a small number of people, and at times effectively one, carried much of the core engineering. When Nikita Popov, who had driven an enormous share of that work, stepped back from full-time PHP development in 2021, ten companies responded by founding the PHP Foundation that November to fund core developers directly. The language is now developed in the open through a public RFC process and is less dependent on any single contributor than it has ever been, which is part of why this guide treats it as a safe long-term choice rather than a legacy language to migrate away from. Modern PHP is statically analyzable, strictly typed where you ask it to be, and competitive in performance with other dynamic languages; almost all of the criticism it still attracts describes the language as it was before 2015. This guide teaches the language as it is today and treats the old patterns only as things to recognize and avoid.

On this history

The dates and milestones above follow the PHP Manual's "History of PHP" appendix and the PHP Foundation's founding announcement of November 2021. The takeaway is not nostalgia: it is that the failures (PHP 6) and the recoveries (phpng to PHP 7, the Foundation) explain why the modern language looks the way it does and why its current trajectory is dependable.

Standard · PHP supported versions and the release cycle

Each PHP release branch receives two years of active support (bug and security fixes) followed by two years of security-only fixes, for a four-year total. As of June 2026 the supported branches are 8.2 (security-only, end of life 31 December 2026), 8.3 (security-only), 8.4 (active support through 31 December 2026), and 8.5 (the current release, active through 31 December 2027). Running an end-of-life branch means running with known, unpatched vulnerabilities.php.net, "Supported Versions" (supported-versions.php), retrieved June 2026. Target 8.4 or 8.5 for new work. 8.4 is a defensible conservative default for its maturity and broad extension compatibility, but note that its active support ends 31 December 2026; 8.5 has the longer remaining support (active through 2027, security-only through 2029), so weigh it for work that starts late in 2026.

This guide targets PHP 8.4 as its baseline, and nothing in it depends on an 8.5-only feature: everything shown works on both. For orientation, 8.5's headline additions are the pipe operator (|>), array_first() and array_last(), a clone-with-properties syntax, and a built-in URI parsing extension (php.net, PHP 8.5 Release Announcement); none of them changes the practices taught here. Where a feature requires a specific version, that is stated.

1.2 Where PHP Runs: the SAPIs

PHP is not a single program. The engine is embedded into a host through a Server Application Programming Interface, or SAPI, and the SAPI determines how PHP receives a request and returns a response. You will meet four, and you only need two.

The CLI SAPI (php on the command line) runs a script to completion and exits. You use it for scripts, build tasks, database migrations, queue workers, and the test suite. The built-in web server (php -S) is a CLI feature that serves HTTP for local development only; it is single-process and explicitly not for production. The PHP-FPM SAPI (FastCGI Process Manager) is how PHP runs on essentially every modern production server: a pool of long-lived PHP worker processes sits behind a web server (nginx or Apache) and answers requests over the FastCGI protocol. PHP-FPM is the entire subject of Chapter 19. The legacy Apache module (mod_php) embeds PHP directly inside each Apache process; it still works but couples PHP's lifecycle to the web server, cannot run as a separate user per site, and is no longer the recommended deployment. This guide uses FPM throughout and treats mod_php as legacy.

Why the SAPI matters to you now

The same script behaves slightly differently per SAPI: php://stdin exists under CLI but not FPM, the working directory and available superglobals differ, and configuration can be set per SAPI. When you read later that a directive applies "only to FPM" or "only to CLI," this is why.

1.3 The Request Lifecycle: Shared-Nothing

This is the single most important idea in the guide. In the model PHP was built for, every request starts from a clean slate. When a request arrives, the engine parses (or loads from cache) the scripts it needs, runs them top to bottom, sends the output, and then destroys everything: every variable, every object, every loaded class is gone. The next request begins with nothing carried over in memory. This is called the shared-nothing architecture.

Compare this to a long-running application server in many other ecosystems, where the process boots once and then handles request after request, holding objects and connections in memory between them. PHP does the opposite, and the consequences run through everything that follows. Because nothing survives a request, any state you need between requests must live somewhere external: a database, a cache like Redis, the session store, or a file. Because the engine would otherwise re-parse every script on every request, an opcode cache (OPcache) is essential, and tuning it is a real performance lever (Chapter 22). Because each request is independent and holds no shared memory, PHP scales horizontally with almost no effort: add another worker, or another machine, and there is no shared in-memory state to coordinate. The cost is that "just keep it in a variable" is never an option across requests, and habits from stateful frameworks do not transfer.

Best practice: design for statelessness from line one

Treat each request as if the process will be killed the moment it finishes, because under FPM it effectively is recycled. Never assume a global, a static property, or an open connection persists to the next request. Code written this way is correct on one server and scales to a hundred without changes; code that assumes persistence breaks the moment a load balancer sends the next request to a different worker.

1.4 Installing PHP

Install the CLI and the FPM package from your distribution. The package names are the main thing that differs between families.

# Debian / Ubuntu family (apt)
# apt update
# apt install -y php8.4-cli php8.4-fpm php8.4-mbstring php8.4-xml php8.4-curl php8.4-mysql php8.4-sqlite3

# RHEL / Fedora family (dnf). On RHEL/Alma/Rocky, enable a recent module or the Remi repo first.
# dnf install -y php-cli php-fpm php-opcache php-mbstring php-xml php-pdo php-mysqlnd

Installing the CLI, FPM, and the handful of extensions almost every project needs.

The labs and the test suite in this guide use SQLite as a zero-setup database (from Chapter 7 onward), so the Debian/Ubuntu line includes php8.4-sqlite3, which provides the pdo_sqlite driver. On the RHEL/Fedora family the php-pdo package above already bundles pdo_sqlite, so no separate package is needed there (under some Remi configurations it is split into php-sqlite3; confirm with dnf search php\* | grep -i sqlite). Without that driver the first database lab fails with could not find driver.

Confirm the version and look at what is compiled in:

$ php --version
PHP 8.4.21 (cli) (built: ...) (NTS ...)
Zend Engine v4.4.21, Copyright (c) Zend Technologies
    with Zend OPcache v8.4.21
$ php -m  # list loaded extensions
$ php --ini  # show which php.ini files are loaded, and from where

The NTS in the banner means "non-thread-safe," which is the correct build for FPM (one request per process, no threads). The --ini output tells you exactly which configuration files the CLI reads; FPM reads a different set, a distinction that causes real confusion and is covered in Chapter 11.

1.5 Your First Script

A PHP file is plain text that the engine reads in "HTML mode" until it sees the opening tag <?php, at which point it switches to executing code until the file ends or it meets a closing ?> tag. A file that is pure PHP should omit the closing tag entirely (the reason is explained in Section 2.1). Create hello.php:

// hello.php
<?php

declare(strict_types=1);

echo "Hello from PHP " . PHP_VERSION . "\n";

Run it with the CLI:

$ php hello.php
Hello from PHP 8.4.21

Now serve it over HTTP with the built-in development server. From the directory containing the file:

$ php -S 127.0.0.1:8000
[PHP 8.4.21 Development Server (http://127.0.0.1:8000) started]
$ curl -s http://127.0.0.1:8000/hello.php
Hello from PHP 8.4.21
Caution: the built-in server is for development only

php -S is single-threaded, serves one request at a time, and has none of the process management, security, or performance characteristics of a real deployment. It is invaluable for local work and never appropriate for production. Production means PHP-FPM behind nginx or Apache, which is exactly what Part VI builds.

That declare(strict_types=1) on the first line is not decoration; it changes how PHP treats types for the whole file, and it is the first habit this guide insists on. The next chapter explains what it does and why it matters.

Exercise 1.1

Run php --ini and note the path of the "Loaded Configuration File." Then run php -i | grep -i opcache.enable. Is OPcache enabled for the CLI? (It usually is not, by design, because short-lived CLI scripts do not benefit.) You will revisit both facts when you tune OPcache for FPM in Chapter 22.

Chapter 2The Language Core

This chapter teaches enough PHP to read and write real code, organized around the language's type system because that is where correctness and security begin.

The goal is not to catalog every function (the PHP Manual does that, exhaustively and well) but to give you an accurate mental model: how values are typed, how comparison works, where the historical foot-guns are, and how modern PHP lets you turn them off.

2.1 Syntax, Tags, and Output

Code lives between <?php and the end of the file. Statements end with a semicolon. Comments are // or # to end of line, or /* ... */ for blocks. You produce output with echo. PHP can interleave with HTML, which is its original purpose: outside the tags, text is sent verbatim; inside, it is executed.

<?php declare(strict_types=1); ?>
<p>The time is <?= date('H:i') ?> on the server.</p>

The short form <?= ... ?> is shorthand for <?php echo ...; ?> and is the correct, always-available way to print a value into a template. A file that contains only PHP (a class, a function library, a configuration array) must omit the closing ?>. Any whitespace or newline after a closing tag is sent to the browser as output, and a stray newline after ?> at the end of an included file is the classic cause of the "headers already sent" error, because output has begun before your code tried to set a header.

2.2 Variables, Types, and the Comparison Trap

Variables start with $ and need no declaration. PHP has ten types (counting the callable and iterable pseudo-types and the rarely handled resource), of which the scalars (int, float, string, bool), null, array, and object are the ones you use constantly. PHP is dynamically typed: a variable's type follows its current value. It is also, by default, weakly typed: it will silently convert between types in many operations, a behavior called type juggling.

Type juggling is the source of PHP's most surprising bugs, and they cluster around the loose equality operator ==, which compares values after converting them to a common type. The identity operator === compares value and type with no conversion. The rule is simple and you should adopt it permanently:

$ php -r 'var_dump(0 == "");'  // PHP 8: false (fixed; was true before 8.0)
$ php -r 'var_dump("1e2" == "100");'  bool(true)  // both look numeric, compared as numbers
$ php -r 'var_dump(0 === "0");'        bool(false)  // different types, no juggling
Best practice: always use === unless you have a specific reason not to

Default to === and !== for every comparison. Loose == has legitimate uses but they are rare and deliberate. Using identity comparison by default removes an entire class of authentication and authorization bugs, including the historical pattern where a hash that began with 0e compared equal to another such hash under == because both were read as the float zero.

PHP 8 substantially repaired the comparison rules: a number compared to a non-numeric string now compares as strings rather than coercing the string to zero, which removed the worst surprise. The repair is welcome, but the discipline of identity comparison remains correct.

2.3 Declaring Types and strict_types

Since PHP 7 you can declare the types of function parameters, return values, and (since 7.4) class properties. By default these declarations operate in coercive mode: if you pass "5" to a parameter typed int, PHP converts it. Adding declare(strict_types=1) as the first statement of a file switches that file to strict mode, in which a type mismatch throws a TypeError instead of silently converting. The declaration affects calls made from that file, which is why it belongs at the top of every file you write.

Standard · PHP Manual: strict typing

The PHP Manual (Language Reference, "Type declarations / Strict typing") specifies that with strict_types=1 the engine enforces declared scalar types exactly, with the single accommodation that an int is accepted where a float is declared. The manual notes the declaration is per file and affects the function calls written in that file, not the function definitions. Strict mode turns type errors into immediate, locatable exceptions rather than data corruption discovered later.php.net Language Reference, "Type declarations," section "Strict typing." This guide enables strict types in every example for that reason.

// money.php
<?php
declare(strict_types=1);

function add_cents(int $a, int $b): int
{
    return $a + $b;
}

echo add_cents(199, 50), "\n";  // 249
echo add_cents("199", 50);  // TypeError: argument 1 must be of type int, string given

The second call is a bug, and strict mode reports it at the call site instead of quietly coercing "199" and hiding the problem. In a money calculation, that difference is the difference between a caught error and a wrong invoice.

2.4 Strings and Arrays: the Two Workhorses

Strings can be single-quoted (literal, no interpolation) or double-quoted (escape sequences and variable interpolation). For multi-line text, heredoc (<<<TAG, interpolating) and nowdoc (<<<'TAG', literal) are clearer than concatenation. PHP strings are byte strings, not Unicode strings, so any work with user-facing text that may be UTF-8 should use the mb_* functions (mb_strlen, mb_substr) from the mbstring extension, which count characters rather than bytes.

<?php
$name = "Ada";
echo "Hello, $name\n";  // interpolates: Hello, Ada
echo 'Hello, $name' . "\n";  // literal:      Hello, $name
echo strlen("naïve"), " ", mb_strlen("naïve"), "\n";  // 6 5 (bytes vs characters)

The array is PHP's central data structure and it is unusual: a single array type serves as both an ordered list (integer keys 0,1,2,...) and a string-keyed map, and it preserves insertion order. You will use it everywhere until you reach objects.

<?php
$list = ['eggs', 'milk', 'bread'];  // indexed
$prices = ['eggs' => 3.20, 'milk' => 1.80];  // associative

$list[] = 'butter';  // append
foreach ($prices as $item => $cost) {
    printf("%-6s %5.2f\n", $item, $cost);
}

[$first, $second] = $list;  // list destructuring
$total = array_sum($prices);  // 5.00

The standard library has hundreds of array functions (array_map, array_filter, array_reduce, array_column, usort, and so on). Their naming and argument order are inconsistent for historical reasons; keep the manual open and do not try to memorize them.

2.5 Control Flow

The conditional and loop constructs are conventional: if/elseif/else, while, for, and foreach for iterating arrays and objects. Two modern additions are worth singling out. The match expression (PHP 8) compares with identity (===), returns a value, requires no break, and throws if no arm matches, which makes it safer than the older switch:

<?php
$label = match ($status) {
    200, 204 => 'OK',
    404      => 'Not Found',
    500      => 'Server Error',
    default  => 'Unknown',
};

The null-coalescing operator ?? returns its right side when the left is null or undefined, which replaces a great deal of isset() boilerplate, and ?-> (nullsafe) short-circuits a method or property access on null instead of erroring.

2.6 Functions

Functions declare parameter and return types, support default values, variadics (...$rest), named arguments at the call site, and union or nullable types. Anonymous functions (closures) capture variables with use; arrow functions (fn() =>) capture the enclosing scope automatically and are ideal for short callbacks.

<?php
declare(strict_types=1);

function format_money(int $cents, string $symbol = '$'): string
{
    return $symbol . number_format($cents / 100, 2);
}

echo format_money(1299);  // $12.99
echo format_money(cents: 990, symbol: '€');  // named arguments: €9.90

$totals = array_map(fn(int $c): string => format_money($c), [199, 250, 1000]);

Named arguments make a call self-documenting and let you skip optional parameters you do not want to set. Arrow functions keep callbacks readable. Both are everyday tools in modern PHP, not advanced features.

Lab 1 · A first Ledger script

Goal: write and run a small procedural PHP script that models a few invoice line items, so you have hands-on contact with types, arrays, and functions before introducing structure.

  1. Create a directory grimoire-ledger and a file tot.php inside it, beginning with <?php and declare(strict_types=1);.
  2. Define an array of line items, each an associative array with description (string) and cents (int): for example three items totaling a few thousand cents.
  3. Write a function subtotal(array $items): int that sums the cents values with array_sum(array_column($items, 'cents')).
  4. Write format_money(int $cents): string as in Section 2.6 and print each line item and the subtotal.
  5. Run it with php tot.php. Then deliberately pass a string where an int is expected and confirm strict mode throws a TypeError rather than producing a wrong total.
Exercise 2.1

Predict the output of var_dump("10 apples" == 10) and var_dump("10 apples" === 10) on PHP 8.4, then run them with php -r. Explain in one sentence why the first is now false when it would have been true before PHP 8.0, and why this is an argument for never relying on ==.

Chapter 3Composer, Autoloading & Project Structure

A single script is not a project.

The moment you want a second file, a third-party library, or a class loaded on demand, you need the two tools that define how modern PHP is assembled: Composer for dependencies and autoloading, and the PSR-4 standard that maps class names to file paths. This chapter installs both, explains the standard project layout every framework follows, and rebuilds the Grimoire Ledger as a structured application you will grow for the rest of the guide.

3.1 The Problem Composer Solves

Before Composer (released 2012), reusing code meant downloading libraries by hand, dropping them into your tree, and writing long chains of require statements in the right order. Versions and transitive dependencies were managed by hope. Composer replaced all of that with a single declarative file. You name the packages and version constraints you want; Composer resolves the whole dependency graph, downloads exact versions, and generates one autoloader that knows where every class lives. It is not optional knowledge: every framework, every serious library, and every deployable PHP application is built on it.

3.2 Installing Composer and Declaring a Project

Composer is a single PHP program (a PHAR). Install it from getcomposer.org following the official signature-verified instructions, then make it global as composer. Initialize a project interactively:

$ composer init  # prompts for name, type, dependencies; writes composer.json
$ composer require ramsey/uuid  # adds a dependency and updates the lockfile

This produces two files. composer.json is your declaration of intent: the package name, the PHP version constraint, your dependencies with version ranges, and your autoloading rules. composer.lock records the exact versions Composer resolved, including every transitive dependency and a content hash. The distinction is critical for reproducible deployments.

Standard · Semantic Versioning and the lockfile contract

Composer version constraints follow Semantic Versioning (SemVer 2.0.0): given MAJOR.MINOR.PATCH, a major bump signals a breaking change, minor adds features compatibly, and patch fixes bugs compatibly. The caret constraint ^1.4 means "at least 1.4, below 2.0." In development you run composer update to move within those ranges and refresh composer.lock; in deployment you run composer install, which installs the exact versions pinned in the lockfile and never resolves anew. Commit composer.lock for applications so every environment is byte-identical.semver.org, Semantic Versioning 2.0.0; Composer documentation, "Versions and constraints" and "composer.lock." The application-versus-library distinction matters: libraries do not commit a lockfile, applications always do.

Caution: install in production, never update

A deployment that runs composer update can silently pull newer dependency versions than you tested, which is how a working build becomes a broken or compromised one. Production deploys run composer install --no-dev --optimize-autoloader: exact locked versions, no development tools, and a fast classmap autoloader. The supply-chain implications of this are revisited under OWASP A03 in Chapter 8.

3.3 Namespaces

A namespace is a prefix that prevents your Invoice class from colliding with a library's Invoice class. By convention the top-level namespace is your vendor or application name. A class is identified by its fully qualified name, the namespace plus the class: App\Billing\Invoice. The use statement imports a name so you can refer to it by its short form within a file.

// src/Billing/Invoice.php
<?php
declare(strict_types=1);

namespace App\Billing;

final class Invoice
{
    public function __construct(
        public readonly string $number,
        public readonly array $lines = [],
    ) {}
}

3.4 PSR-4 Autoloading

Autoloading is the mechanism by which referring to a class causes PHP to find and load the file that defines it, with no manual require. The ecosystem standard for the mapping is PSR-4, and Composer implements it from a few lines in composer.json.

Standard · PSR-4: Autoloader

PSR-4 (PHP-FIG, accepted) specifies how a fully qualified class name maps to a file path: a registered namespace prefix corresponds to a base directory, and the remaining namespace segments after the prefix map directly to subdirectories, with the class name plus .php as the file. Given the rule "App\\": "src/", the class App\Billing\Invoice must live at src/Billing/Invoice.php. Exactly one class per file, named to match. This convention is what lets any tool, framework, or IDE locate your code without configuration.PHP-FIG PSR-4, "Autoloader." PSR-4 supersedes the deprecated PSR-0. The mapping is purely lexical: get the namespace-to-directory correspondence right and autoloading is automatic.

// composer.json (excerpt)
{
    "name": "grimoire/ledger",
    "require": { "php": ">=8.4" },
    "autoload": {
        "psr-4": { "App\\": "src/" }
    }
}

After editing the autoload rules, run composer dump-autoload to regenerate the autoloader. From then on, your entry point includes Composer's autoloader once and every class loads on demand:

<?php
require __DIR__ . '/../vendor/autoload.php';  // the only require you write

use App\Billing\Invoice;
$inv = new Invoice('2026-0001');

3.5 The Standard Project Layout

Every modern PHP application shares the same skeleton, and frameworks differ only in detail. Learn it once here and Laravel and Symfony in Part IV will look familiar.

The conventional PHP project layout and why each part exists.
PathPurpose
public/The only directory the web server exposes. Holds index.php (the front controller) and static assets. Everything else is above the web root and unreachable by URL.
src/Your application's PHP classes, PSR-4 autoloaded. No directly executable scripts.
vendor/Composer-installed dependencies and the generated autoloader. Never edited by hand; never committed (it is rebuilt by composer install).
tests/The test suite (Chapter 6).
config/, .envConfiguration and environment-specific secrets. The .env file is never committed.
composer.json, composer.lockDependency declaration and the exact resolved versions.
Standard · OWASP A02:2025 (Security Misconfiguration): keep code above the web root

Exposing only public/ is a security control, not just tidiness. If the document root is the project root, a misconfigured handler can serve your source, your .env secrets, or composer.lock as plain text. Placing the front controller in public/ and pointing the web server there means a request can only reach files you deliberately published. This is the foundational mitigation for the "files placed in the web root" class of OWASP A02:2025, Security Misconfiguration.OWASP Top 10:2025, A02 Security Misconfiguration. The web-server configuration that enforces this is shown for both nginx and Apache in Chapter 20.

3.6 The Running Example: the Grimoire Ledger

From here on, the worked example is the Grimoire Ledger: a small application that records invoices and their line items. It starts now as a structured, Composer-managed project with a front controller, and it grows through the guide. In Part II it gains typed domain classes, a logger, tests, and a transactional database layer. In Part III it is secured with prepared statements, output encoding, hardened sessions, and a hardened runtime. In Part IV it is rebuilt in both Laravel and Symfony and exposed as a JSON API. In Part VI it is served by FPM pools, containerized, and scaled. In Part VII it grows background workers, observability, and a deployment pipeline, and is the system you learn to upgrade when it ages. The point of one running example is that you see the same application at every altitude, so each layer connects to the last.

# the Ledger skeleton after this chapter
grimoire-ledger/
├── public/
│   └── index.php  # front controller: the only entry point
├── src/
│   └── Billing/
│       ├── Invoice.php
│       └── LineItem.php
├── tests/
├── composer.json
└── composer.lock

The front controller is deliberately tiny at this stage; it will become a router in the framework chapters. Its job is to be the single door through which every request enters.

// public/index.php
<?php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use App\Billing\Invoice;
use App\Billing\LineItem;

$invoice = new Invoice('2026-0001', [
    new LineItem('Consulting, June', 120000),
    new LineItem('Hosting',            4500),
]);

header('Content-Type: text/plain; charset=utf-8');
echo "Invoice {$invoice->number}\n";
Lab 2 · Stand up the Ledger as a Composer project

Goal: convert the Lab 1 script into a real project with Composer, PSR-4 autoloading, a dependency, and a front controller served by the development server.

  1. In grimoire-ledger/, run composer init; set the name to grimoire/ledger and require PHP >=8.4.
  2. Add the autoload rule "psr-4": { "App\\": "src/" } to composer.json and run composer dump-autoload.
  3. Create src/Billing/Invoice.php and src/Billing/LineItem.php as classes in namespace App\Billing (use constructor property promotion and readonly as shown; Chapter 4 explains both).
  4. Run composer require ramsey/uuid and give each invoice a generated UUID, to prove a third-party class autoloads with no require.
  5. Create public/index.php as the front controller and serve it with php -S 127.0.0.1:8000 -t public. Confirm curl http://127.0.0.1:8000/ prints the invoice. Note that -t public sets the web root to public/, so src/ is unreachable by URL.
Exercise 3.1

Delete the generated vendor/ directory and run composer install. Did your application still work, and where did the exact dependency versions come from? Now open composer.lock and find the entry for ramsey/uuid: note that it records a specific version and an integrity hash. Explain why committing this file is what makes a deployment reproducible.

Part II Writing Modern, Standards-Compliant PHP

Knowing the syntax is not the same as writing PHP that a team can maintain and a tool can analyze. This part covers the craft. Chapter 4 teaches object-oriented PHP and the modern language features (enums, readonly properties, attributes) that the frameworks in Part IV are built from. Chapter 5 introduces the PHP-FIG standards, the coding style the whole ecosystem agreed on and the shared interfaces that let independent libraries work together, plus the tools that enforce all of it automatically. Chapter 6 covers the unglamorous disciplines that separate a prototype from production code: error handling, structured logging, and tests. Chapter 7 gives the running application a deliberate data layer: PDO, transactions, hydration back into the typed domain, the repository pattern, and schema migrations.

Chapter 4Object-Oriented and Modern PHP

Modern PHP is an object-oriented language with a capable type system.

This chapter teaches the object model and the post-8.0 features that define how current code looks, using the Grimoire Ledger's domain to make each one concrete. By the end you can write the typed, immutable value objects and the interface-driven services that the rest of the guide depends on.

4.1 Classes, Visibility, and Promotion

A class bundles data (properties) and behavior (methods). Each member has a visibility: public (reachable anywhere), protected (the class and its subclasses), or private (the declaring class only). Default to private and widen only when you must; a narrow surface is easier to reason about and to change. Constructor property promotion (PHP 8.0) collapses the common pattern of declaring a property, accepting it as a parameter, and assigning it, into a single declaration in the constructor signature.

// the verbose, pre-8.0 form
final class LineItem
{
    private string $description;
    private int $cents;
    public function __construct(string $description, int $cents)
    {
        $this->description = $description;
        $this->cents = $cents;
    }
}

// the same class with constructor property promotion (8.0+)
final class LineItem
{
    public function __construct(
        private string $description,
        private int $cents,
    ) {}
}

Marking a class final declares that it is not meant to be extended. Preferring final by default is a deliberate design stance: it makes inheritance an opt-in decision rather than an accident, and it pushes you toward composition, which is easier to test and change.

4.2 Immutability with readonly

A readonly property can be written once, during initialization, and never again. It is the cleanest way to build value objects: small, immutable objects defined entirely by their values. PHP 8.2 added readonly classes, which mark every property readonly at once. Immutability removes a whole category of bugs in which an object is mutated unexpectedly by code far away.

Standard · PHP Manual: readonly properties

The PHP Manual (Classes and Objects, "Readonly properties") specifies that a readonly property may be initialized only once, and only from within the scope where it is declared; any later write throws an Error. Readonly properties must be typed. A readonly class (8.2+) applies the modifier to all declared properties. The manual notes readonly prevents reassignment of the property, not deep mutation of a mutable object it holds, so value objects should hold only scalars or other immutable values.php.net, Classes and Objects, "Readonly properties" and "Readonly classes." Immutability is a correctness tool first and a concurrency aid second; in PHP's shared-nothing model the latter matters less, but the former matters everywhere.

// src/Billing/Money.php  --  an immutable value object
<?php
declare(strict_types=1);

namespace App\Billing;

final readonly class Money
{
    public function __construct(
        public int $cents,
        public string $currency = 'USD',
    ) {
        if ($cents < 0) {
            throw new \InvalidArgumentException('Money cannot be negative.');
        }
    }

    public function add(Money $other): self
    {
        $this->assertSameCurrency($other);
        return new self($this->cents + $other->cents, $this->currency);
    }

    public function format(): string
    {
        return number_format($this->cents / 100, 2) . ' ' . $this->currency;
    }

    private function assertSameCurrency(Money $other): void
    {
        if ($this->currency !== $other->currency) {
            throw new \DomainException('Currency mismatch.');
        }
    }
}

Notice that add() returns a new Money rather than mutating $this. Operations on immutable objects produce new values, exactly like arithmetic on integers. This is the pattern you want for anything that represents a quantity or an identity. Note too that the amount lives as an integer number of cents and a float appears only in format(), at the display boundary, never in arithmetic, which keeps money math free of floating-point rounding error.

4.3 Interfaces: Program to a Contract

An interface is a pure contract: a set of method signatures with no implementation. A class that implements an interface promises to provide those methods. The value is decoupling: code that depends on an interface can work with any implementation, which is what makes systems testable (swap a real implementation for a fake in a test) and flexible (swap one database or mailer for another without touching the callers).

<?php
declare(strict_types=1);

namespace App\Billing;

interface InvoiceRepository
{
    public function save(Invoice $invoice): void;
    public function find(string $number): ?Invoice;
}

Now a controller can depend on InvoiceRepository without knowing or caring whether invoices are stored in PostgreSQL, in memory for a test, or in a remote API. This "depend on abstractions" principle is the backbone of the dependency injection that both frameworks in Part IV provide, and it is formalized by the PSR-11 container interface in Chapter 5.

4.4 Traits, and When Not to Use Them

A trait is a unit of methods that can be mixed into multiple classes, a way to share implementation horizontally where inheritance does not fit. Traits are useful for genuinely cross-cutting helpers, but they are easy to abuse: a trait that touches the host class's properties creates a hidden coupling that is hard to follow. Prefer composition (hold a collaborator object) over a trait whenever the shared code has its own state or responsibility.

Best practice: reach for composition before traits or inheritance

When you want to reuse behavior, the default question is "can this be a separate object that I hold and call?" If yes, compose it. Use inheritance only for genuine "is-a" relationships and traits only for stateless, cross-cutting mixins. Codebases that lean on deep inheritance or fat traits become difficult to test precisely because the behavior is spread across the hierarchy rather than located in collaborators you can substitute.

4.5 Enumerations

Enums (PHP 8.1) give you a fixed, type-safe set of named values, replacing the old habit of loose class constants or bare strings. A pure enum has named cases; a backed enum assigns each case a scalar (string or int) for storage and serialization. Enums can have methods, which is how you attach behavior to a state.

<?php
declare(strict_types=1);

namespace App\Billing;

enum InvoiceStatus: string
{
    case Draft   = 'draft';
    case Sent    = 'sent';
    case Paid    = 'paid';
    case Overdue = 'overdue';

    public function isFinal(): bool
    {
        return $this === self::Paid;
    }

    public function label(): string
    {
        return match ($this) {
            self::Draft   => 'Draft',
            self::Sent    => 'Awaiting payment',
            self::Paid    => 'Paid in full',
            self::Overdue => 'Overdue',
        };
    }
}

$s = InvoiceStatus::from('paid');  // throws if the value is not a valid case
$s = InvoiceStatus::tryFrom('x');  // returns null instead of throwing

Because InvoiceStatus is a type, a function that accepts InvoiceStatus $status cannot be handed an arbitrary string. The set of valid states is enforced by the language, not by your vigilance, and the match in label() is exhaustive: add a case and forget to handle it and analysis tools flag it.

4.6 Attributes: Structured Metadata

Attributes (PHP 8.0) attach structured, machine-readable metadata to classes, methods, properties, and parameters, written in #[...] syntax. They replace the old practice of encoding metadata in doc-comment text. On their own they do nothing; a framework or library reads them by reflection and acts on them. You will see attributes constantly in Part IV: Symfony uses #[Route] to declare routing and #[Assert\NotBlank] for validation, and Laravel and Doctrine use them similarly.

<?php
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Validator\Constraints as Assert;

final class InvoiceController
{
    #[Route('/invoices/{number}', methods: ['GET'])]
    public function show(string $number): Response { /* ... */ }
}

final class CreateInvoiceRequest
{
    #[Assert\NotBlank]
    #[Assert\Length(max: 16)]
    public string $number = '';
}

The point is that the metadata lives next to the thing it describes and is typed and discoverable, rather than being a magic string in a comment or a separate configuration file far from the code.

Exercise 4.1

Add a Money value object to the Ledger as shown, then change LineItem to hold a Money instead of a bare int. Try to reassign a readonly property after construction and observe the Error. Then add an InvoiceStatus enum to Invoice and write a method that refuses to move a Paid invoice back to Draft. Which language features made the illegal states unrepresentable rather than merely discouraged?

Chapter 5The PSR Coding Standards and the Tools That Enforce Them

PHP has no single vendor, so its consistency comes from a community body: the PHP Framework Interop Group (PHP-FIG), which publishes the PSR specifications.

Two kinds matter. Coding-style PSRs make every codebase look the same so any developer can read any project. Interface PSRs define shared contracts (a logger, an HTTP message, a container) so that independently written libraries interoperate. This chapter covers both, with the current status of each, and then the tools that check and fix your code automatically.

5.1 What a PSR Is, and How to Read Its Status

A PSR (PHP Standard Recommendation) is a numbered specification voted on by PHP-FIG member projects. Each has a status: Accepted (final), Draft/Review (in progress), or Deprecated (superseded). PHP-FIG also now publishes PER documents (PHP Evolving Recommendations), which, unlike a frozen PSR, are versioned and updated as the language evolves. The coding style guidance has moved to a PER for exactly this reason: the language keeps adding syntax that a frozen 2019 document could not anticipate.

5.2 The Coding Style: PSR-1, PSR-12, and PER Coding Style 3.0

Three documents form the style lineage. PSR-1 (Basic Coding Standard) sets the fundamentals: files use <?php or <?= tags only, UTF-8 without BOM, one class per file, StudlyCaps class names, camelCase methods, and a separation between files that declare symbols and files that cause side effects. PSR-12 (Extended Coding Style) built on it with detailed rules for indentation, line length, spacing, and the placement of keywords and braces. PSR-12 is now superseded for active use by the PER Coding Style.

Standard · PER Coding Style 3.0 (supersedes PSR-12)

PER Coding Style 3.0 is the current PHP-FIG coding style. It extends, expands, and replaces PSR-12, and requires adherence to PSR-1. The PER form exists because PSR-12 was accepted in 2019 and could not address syntax added since (enums, readonly, constructor promotion, first-class callable syntax, attributes); the PER is versioned so it can be updated as PHP changes. Core rules include four-space indentation (never tabs), a soft 120-character line target, one statement per line, opening braces for classes and methods on their own line, visibility declared on every property and method, and a defined ordering for the elements of a class declaration.PHP-FIG, "PER Coding Style 3.0" (php-fig.org/per/coding-style). PSR-12 remains published but the PER is the living standard; tooling defaults now target it. Treat PSR-1 as the required base and the PER as the detailed style.

You do not memorize these rules. You configure a tool to enforce them and let it reformat on save and in continuous integration, which is the subject of Section 5.5. The value of a shared style is not aesthetic: it is that a reviewer reads logic instead of arguing about braces, and a diff shows behavior changes instead of reformatting noise.

5.3 The Interface PSRs: How Libraries Interoperate

The interface PSRs are where the ecosystem's real power lives. Each defines a small set of interfaces in a Psr\* namespace, published as a tiny package containing only those interfaces. A library depends on the interface, not on a concrete implementation, so you can supply any compliant implementation. These are the ones you will actually encounter and use.

The PSR interface standards a working PHP developer meets, and what each lets you swap.
PSRDefinesWhy it matters
PSR-3LoggerInterfaceAny library can accept a logger and write to it; you choose the backend (Monolog, etc.). Covered in Chapter 6.
PSR-4AutoloadingClass-name to file-path mapping (Section 3.4). The reason any tool can find your code.
PSR-7HTTP message interfacesA common RequestInterface/ResponseInterface so middleware and frameworks share one representation of an HTTP message.
PSR-15Server request handlers and middlewareThe middleware pipeline model (a request passes through layers) that nearly every modern framework uses.
PSR-17HTTP factoriesConstruct PSR-7 objects without binding to a specific implementation.
PSR-18HTTP clientSend a PSR-7 request through any compliant HTTP client (Guzzle, Symfony HttpClient).
PSR-11ContainerInterfaceA standard get()/has() for dependency-injection containers; the contract behind framework service location.
PSR-6 / PSR-16Caching (pool, and "simple cache")Swap a cache backend (Redis, filesystem, APCu) without changing calling code. Used in Chapter 22.
PSR-14Event dispatcherA standard way to emit and listen for domain events across libraries.

The practical lesson: when you need a logger, a cache, or an HTTP client in your own code, type-hint the PSR interface (Psr\Log\LoggerInterface), not a concrete class. Your code then works with whatever implementation the application provides, and it is trivial to test with a fake.

5.4 Static Analysis: Catching Bugs Without Running Code

A static analyzer reads your code and proves properties about it without executing it: that a method receives the types it declares, that a nullable value is checked before use, that a called method exists, that every match arm is covered. PHPStan and Psalm are the two leading analyzers, and both grade strictness in levels you raise over time. They find real bugs (a typo'd property, an unhandled null, a wrong argument) that tests might miss, and they do it in milliseconds. This section is the introduction; Chapter 18 treats static analysis in full, including the level ladder, docblock generics, Psalm's security taint analysis, and the framework extensions that make a high level usable on Laravel and Symfony.

Best practice: adopt analysis at a low level, then ratchet up

On an existing codebase, start PHPStan at level 0 or use a baseline file that records current issues, get the build green, then raise the level one step at a time. New code should target the highest level the team can sustain (PHPStan level 8 or 9, or Psalm's stricter settings). The combination of declare(strict_types=1) everywhere plus a high analysis level is most of what makes PHP feel like a statically typed language in practice.

5.5 The Toolchain

Four tools, all Composer dev-dependencies, cover style and correctness. Install them into the Ledger and wire them into Composer scripts so the whole team runs the same checks.

The standard PHP quality toolchain.
ToolJob
PHP_CodeSniffer (phpcs/phpcbf) or PHP-CS-FixerDetect and automatically fix coding-style violations against PSR-12 / PER Coding Style.
PHPStan or PsalmStatic analysis: type and logic errors without running the code.
RectorAutomated refactoring and version upgrades (rewrite old syntax to new, apply framework migrations).
PHPUnitThe test runner (Chapter 6).
$ composer require --dev friendsofphp/php-cs-fixer phpstan/phpstan phpunit/phpunit rector/rector
// composer.json: a "scripts" block makes the checks one command each
"scripts": {
    "lint":    "php-cs-fixer fix --dry-run --diff",
    "fix":     "php-cs-fixer fix",
    "analyse": "phpstan analyse src --level=8",
    "test":    "phpunit",
    "check":   ["@lint", "@analyse", "@test"]
}

Now composer check runs style, analysis, and tests together. That single command is what continuous integration runs on every push, and it is the contract that keeps a shared codebase consistent. Part V expands this gate to its full form: deep unit testing (Chapter 16), mutation testing to measure whether those tests are any good (Chapter 17), and the complete static-analysis and security stage (Chapter 18), all bound into one composer check.

Lab 3 · Wire the quality toolchain into the Ledger

Goal: add automated style enforcement and static analysis to the running project and see them catch a real issue.

  1. Run the composer require --dev command above to install PHP-CS-Fixer, PHPStan, and PHPUnit.
  2. Create a minimal .php-cs-fixer.php selecting the PER/PSR-12 rule set, and run composer fix. Observe what it reformats.
  3. Add the scripts block to composer.json and run composer analyse. If PHPStan reports nothing, introduce a bug on purpose (return a string from a method typed int, or read a possibly-null value) and run it again to see the report.
  4. Fix the bug, run composer check, and confirm all three stages pass. This is the green build every later chapter assumes.
Exercise 5.1

In your own words, explain the difference between a coding-style PSR (PSR-12 / PER) and an interface PSR (PSR-3, PSR-7). Why can a style violation never break another library at runtime, while an interface mismatch can? Which kind does PHPStan check, and which does PHP-CS-Fixer check?

Chapter 6Errors, Exceptions, Logging & Testing

Production code fails, and the difference between a robust application and a fragile one is how it fails: whether errors surface as locatable exceptions or silent wrong answers, whether they are logged in a form you can search, and whether a test would have caught the regression.

This chapter covers PHP's error model, structured logging to the PSR-3 standard, and testing with PHPUnit, all on the Grimoire Ledger.

6.1 Errors and Exceptions: One Hierarchy

Since PHP 7, almost everything that can be thrown implements the Throwable interface, which has two branches. Exception is for conditions your code raises and is expected to handle (a validation failure, a missing record). Error is for engine-level problems (a TypeError from strict types, a call to an undefined method); you generally do not catch these, you fix the code that caused them. Both can be caught with catch (\Throwable $e) when you truly need a last-resort handler. For the application-wide backstop that catches whatever reaches the top of the stack, register a global handler with set_exception_handler() (and set_error_handler() to funnel legacy errors through the same path); a framework installs one for you, and a no-framework application should install its own so nothing escapes unlogged.

<?php
try {
    $invoice = $repository->find($number);
    if ($invoice === null) {
        throw new InvoiceNotFound($number);
    }
    $invoice->markPaid();
} catch (InvoiceNotFound $e) {
    $logger->warning('Attempt to pay unknown invoice', ['number' => $number]);
    http_response_code(404);
} finally {
    $repository->releaseLock($number);  // runs whether or not an exception was thrown
}

Define your own exception types (here InvoiceNotFound extends \RuntimeException) so callers can catch precisely what they mean to handle. The cardinal sin is the empty catch that swallows an exception and continues as if nothing happened; it converts a loud, locatable failure into a silent data bug that surfaces days later.

Caution: never display raw errors to users in production

An uncaught exception or a PHP error, shown to a visitor, leaks file paths, code structure, and sometimes credentials or query text. The rule is environment-dependent and absolute: in development, display errors to find them fast; in production, never display them, always log them. The exact display_errors, log_errors, and error_reporting settings that enforce this are specified in Chapter 11, and the underlying risk is OWASP A10:2025, Mishandling of Exceptional Conditions, discussed in Chapter 8.

6.2 Structured Logging with PSR-3

Logging is how a stateless, short-lived PHP request leaves a trace you can investigate later. The ecosystem standard is PSR-3, and the near-universal implementation is Monolog. Code that needs to log accepts a Psr\Log\LoggerInterface and calls one of the eight severity methods; the application decides where the records go.

Standard · PSR-3: Logger Interface

PSR-3 (PHP-FIG, accepted) defines LoggerInterface with a method per RFC 5424 severity level (emergency, alert, critical, error, warning, notice, info, debug) plus a generic log(). Messages may contain {placeholder} tokens filled from a context array, which keeps the message template constant while carrying structured data. Crucially, the standard directs that the context array carries the variable data rather than being interpolated into the message string by hand, which is what makes logs machine-parseable and safe.PHP-FIG PSR-3, "Logger Interface," and the placeholder interpolation rules in its specification. Pass data in the context array; never concatenate user input into the message text, which both breaks parsing and can inject forged log lines.

<?php
use Monolog\Handler\StreamHandler;
use Monolog\Level;
use Monolog\Logger;

$log = new Logger('ledger');
$log->pushHandler(new StreamHandler('php://stderr', Level::Info));

// good: constant template, structured context
$log->info('Invoice {number} marked paid', ['number' => $invoice->number, 'cents' => $total]);
Caution: never log secrets or personal data

Logs are read widely and kept a long time, so a password, token, full card number, or unnecessary personal data written to a log is itself an A09:2025 finding. Keep them out of both the message template and the context array, and redact or hash any identifier you do not strictly need; record that an event happened, not its sensitive payload.

Best practice: log to stderr/stdout in containerized and FPM deployments

In a containerized or process-managed deployment, do not write application logs to files inside the container. Write structured records to stderr and let the platform (the container runtime, systemd's journal, or a log shipper) collect, rotate, and centralize them. This is the twelve-factor logging approach and it is what makes logs survive a recycled or rescheduled worker. Centralized, tamper-evident logging is also an OWASP A09:2025 (Security Logging and Alerting Failures) control.

6.3 Testing with PHPUnit

PHPUnit is the standard test framework. A test is a method that exercises a unit of behavior and asserts the result. Tests on pure, typed value objects like Money are fast, deterministic, and exactly the kind of safety net that lets you refactor with confidence. Tests live in tests/, mirror the src/ namespace under a Tests\ prefix, and run with composer test.

// tests/Billing/MoneyTest.php
<?php
declare(strict_types=1);

namespace Tests\Billing;

use App\Billing\Money;
use PHPUnit\Framework\TestCase;

final class MoneyTest extends TestCase
{
    public function test_adds_same_currency(): void
    {
        $sum = (new Money(1299))->add(new Money(1));
        $this->assertSame(1300, $sum->cents);
    }

    public function test_rejects_currency_mismatch(): void
    {
        $this->expectException(\DomainException::class);
        (new Money(100, 'USD'))->add(new Money(100, 'EUR'));
    }

    public function test_rejects_negative_amount(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        new Money(-1);
    }
}

These three tests pin the contract of Money: addition works, currency mixing is refused, negatives are refused. If a later change breaks any of them, the build fails immediately and points at the exact behavior that regressed. That is the entire value of tests, and it compounds: the more behavior you pin, the more aggressively you can change the code underneath.

This is the testing primer. Chapter 16 picks it up in depth: the modern attribute-based test syntax, Pest as an alternative runner, test doubles, data providers, fixtures, testing the database layer, and what code coverage can and cannot tell you. Chapter 17 then measures test quality with mutation testing and tests full Laravel and Symfony applications.

6.4 Putting It in Continuous Integration

The composer check script from Section 5.5 (style, analysis, tests) is what a continuous-integration pipeline runs on every push and every pull request. A change that fails any stage does not merge. This is not ceremony; it is the mechanism that keeps a codebase shippable as it grows and as people come and go. The exact pipeline syntax varies by platform, but the content is always the same three commands you already run locally. Chapter 18 grows this into the full quality gate (adding security taint analysis and a mutation-score floor), and Chapter 26 wires it into a complete deployment pipeline.

Lab 4 · Test and log the Ledger

Goal: add a passing test suite and structured logging to the running project, and confirm both run from Composer.

  1. Add phpunit.xml pointing at tests/ and configure the Tests\ autoload namespace under autoload-dev in composer.json; run composer dump-autoload.
  2. Write tests/Billing/MoneyTest.php as shown and run composer test. Confirm three green tests.
  3. Add composer require monolog/monolog and emit an info log when an invoice total is computed, using a constant message template and a context array (never string concatenation of the values).
  4. Break Money::add() on purpose (drop the currency check) and run composer test; watch the relevant test fail. Restore it and confirm green. This is the regression-detection loop you rely on for every later change.
Exercise 6.1

PSR-3 says to pass variable data in the context array rather than concatenating it into the message string. Give one operational reason (think about searching a million log lines for all events about invoice 2026-0001) and one security reason (think about what a user-controlled value containing a newline could do to a log file) that this rule exists.

Chapter 7Databases & Persistence

The Ledger has had typed domain objects since Chapter 4, but it has never had a deliberate data-access layer: one that opens connections correctly under shared-nothing, groups related writes into transactions so a failure cannot leave a half-written record, turns rows back into the value objects the rest of the code already trusts, and evolves its schema in version control rather than by hand on a server.

This chapter builds that layer on PDO. Every query here uses bound parameters; the full reason, the SQL-injection defense, is the subject of Chapter 9, which later hardens this same layer. This chapter concentrates on the data layer itself: connection lifecycle, transactions, hydration, the repository, and migrations.

7.1 PDO: One API, Many Engines

PHP talks to relational databases through PDO (PHP Data Objects), a single object-oriented interface that speaks to MySQL and MariaDB, PostgreSQL, SQLite, SQL Server, and others through swappable drivers. You learn one API; a connection string called the DSN (data source name) selects the engine and where it lives. Writing against PDO rather than an engine-specific extension (the old mysqli, for example) is what lets the Ledger run on SQLite in a test and PostgreSQL in production with the same code.

// the DSN names the driver and the target; the rest of the code is engine-agnostic
$dsn = 'sqlite:/srv/ledger/var/ledger.db';  // file-backed SQLite (great for tests)
$dsn = 'mysql:host=127.0.0.1;dbname=ledger;charset=utf8mb4';
$dsn = 'pgsql:host=127.0.0.1;dbname=ledger';

Since PHP 8.4 there are two ways to construct a connection. The classic new PDO($dsn, $user, $pass, $options) returns a generic PDO object and is the right choice when you want code that does not care which engine is behind it. The newer PDO::connect() factory inspects the DSN and returns a driver-specific subclass (Pdo\Mysql, Pdo\Pgsql, Pdo\Sqlite, and the rest), which exposes that engine's own helpers and constants without the old driver-prefixed function names. It is fully backward compatible: existing new PDO() code is unaffected, and you reach for the factory only when you want the engine-specific surface.

Standard · PHP Manual: PDO and the 8.4 driver subclasses

The PHP Manual specifies PDO as the database-access abstraction and documents its connection options. As of PHP 8.0 the default error mode is PDO::ERRMODE_EXCEPTION, so a failed query throws a PDOException rather than silently returning false; this guide sets it explicitly for clarity regardless. PHP 8.4 added the PDO::connect() static factory, which returns a driver-specific subclass (Pdo\Mysql, Pdo\Pgsql, Pdo\Sqlite, and others) while leaving the generic new PDO() constructor unchanged and fully supported.php.net, PDO documentation; php.net Manual, "Migrating from PHP 8.3.x to PHP 8.4.x, New Features" (PDO driver-specific subclasses). The security rationale for the three production connection options below is given in Section 9.2.

<?php
declare(strict_types=1);

// the production connection options (the injection rationale is in Section 9.2)
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,  // throw on error (default since 8.0)
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,  // associative rows by default
    PDO::ATTR_EMULATE_PREPARES   => false,  // real server-side prepares, correct types
];

$pdo = new PDO($dsn, $user, $pass, $options);  // engine-agnostic; or PDO::connect() for a subclass

7.2 Connections in a Shared-Nothing World

The execution model from Section 1.3 governs how you treat a connection. Under FPM a request opens its database connection, uses it, and the engine tears it down when the request ends; nothing is carried to the next request. The correct mental model is one connection per request, constructed once near the start and passed (injected) to the code that needs it, never stashed in a global in the hope of reuse. That hope does not survive shared-nothing anyway.

PHP does offer persistent connections (PDO::ATTR_PERSISTENT => true), which keep the underlying connection open in the worker and reuse it across requests. The throughput appeal is real, and so are the hazards: a connection handed back to the pool can carry leftover session settings, an open transaction, temporary tables, or a held lock into an unrelated later request, and the count of live connections becomes pm.max_children multiplied by the number of servers, which can quietly exceed the database's connection limit. This is the same pressure described from the scaling side in Section 22.5.

Caution: prefer an external pooler to PHP persistent connections

If connection setup cost is genuinely your bottleneck, put a dedicated pooler between PHP and the database (PgBouncer for PostgreSQL, ProxySQL for MySQL) rather than turning on ATTR_PERSISTENT. A pooler manages connection reuse and reset correctly and gives you one place to cap total connections; PHP persistent connections push that responsibility into every worker and leak state when an application does not reset it. Reach for persistence only with measurement in hand and the state hazards understood.

7.3 Statements, Binding, and Hydration

Every query is a prepared statement with bound parameters; that is non-negotiable and the reason is in Section 9.2. What this chapter adds is shape: how you bind, fetch, and turn rows back into the typed domain. Placeholders come in two forms, named (:number) and positional (?); named placeholders read better in anything beyond a trivial query. You pass the values to execute() as an array, and PDO keeps them strictly separate from the SQL text.

<?php
$stmt = $pdo->prepare(
    'SELECT number, status, note FROM invoices WHERE status = :status ORDER BY number'
);
$stmt->execute(['status' => $status->value]);  // bind the backed-enum's scalar value
$rows = $stmt->fetchAll();  // each row is an associative array

The more important discipline is hydration: rows arrive as arrays of scalars, but the rest of the Ledger works with the typed value objects from Chapter 4, so the data layer is the boundary where the two meet. Map each row explicitly through the object's constructor rather than letting PDO populate properties for you. PDO's FETCH_CLASS mode can build objects directly, but by default it assigns the column values to the object's properties before the constructor runs, so the validation that makes Money trustworthy (its refusal of negative amounts) never gets to gate what came out of the database. The FETCH_PROPS_LATE flag reverses that order so the constructor runs first, but for value objects with real invariants, explicit hydration through the constructor is clearer and keeps those guarantees in force.

<?php
declare(strict_types=1);

// turn a raw row into domain objects, so invariants are enforced on the way in
function hydrateInvoice(array $row, array $lineRows): Invoice
{
    $lines = array_map(
        static fn(array $r): LineItem => new LineItem($r['description'], new Money((int) $r['cents'])),
        $lineRows,
    );
    return new Invoice($row['number'], $lines, InvoiceStatus::from($row['status']));
}

7.4 Transactions: All or Nothing

An invoice and its line items are a single fact about the world. Writing the invoice row and then failing before the line items are written leaves a record that is internally false: an invoice with no lines, or worse, some of them. A transaction makes a group of statements atomic, so either every change commits or none does. You begin a transaction, do the writes, and commit; if anything throws, you roll back and the database is left exactly as it was before you started.

Standard · PHP Manual: PDO transactions, and the engine's guarantees

The PHP Manual documents PDO::beginTransaction(), PDO::commit(), and PDO::rollBack() as the control surface for the database's transactional guarantees, summarized as ACID: atomicity (all or nothing), consistency (constraints hold across the change), isolation (concurrent transactions do not see each other's partial work), and durability (a committed change survives a crash). Two engine facts matter in practice. The guarantees are the database's, not PHP's: on MySQL they require a transactional storage engine (InnoDB, the default; the legacy MyISAM silently ignores transactions), while SQLite and PostgreSQL are transactional throughout. And on MySQL, data-definition statements (CREATE, ALTER, DROP) cause an implicit commit, so schema changes cannot be rolled back inside a transaction.php.net, "PDO::beginTransaction," "PDO::commit," "PDO::rollBack," and the PDO transactions and autocommit documentation. PDO does not provide true nested transactions; a second beginTransaction() throws, and partial rollback within a transaction is done with SQL SAVEPOINTs.

<?php
declare(strict_types=1);

// save an invoice and its lines as one atomic unit
$pdo->beginTransaction();
try {
    $pdo->prepare('INSERT INTO invoices (number, status, note) VALUES (:number, :status, :note)')
        ->execute([
            'number' => $invoice->number,
            'status' => $invoice->status->value,
            'note'   => $invoice->note,
        ]);

    $insertLine = $pdo->prepare(
        'INSERT INTO line_items (invoice_number, description, cents) VALUES (:inv, :desc, :cents)'
    );
    foreach ($invoice->lines as $line) {
        $insertLine->execute([
            'inv'   => $invoice->number,
            'desc'  => $line->description,
            'cents' => $line->amount->cents,
        ]);
    }

    $pdo->commit();
} catch (\Throwable $e) {
    $pdo->rollBack();  // leave the database exactly as it was
    throw $e;  // never swallow it: a failed save must be loud (Chapter 6)
}

The shape is always the same: begin, write, commit inside a try; roll back and rethrow inside the catch. Rethrowing matters, because a save that failed must surface as the locatable exception Chapter 6 argued for, not a quiet return that the caller mistakes for success.

7.5 The Repository Pattern in Practice

All of this belongs behind the InvoiceRepository interface declared back in Section 4.3. A repository is the one place that knows SQL; the rest of the application depends on the interface and stays ignorant of the database. That is what the interface bought you: a controller asks for an InvoiceRepository, and it neither knows nor cares that the implementation is PDO, an in-memory array in a test, or a different engine tomorrow.

// src/Billing/PdoInvoiceRepository.php
<?php
declare(strict_types=1);

namespace App\Billing;

final class PdoInvoiceRepository implements InvoiceRepository
{
    public function __construct(private \PDO $pdo) {}

    public function save(Invoice $invoice): void
    {
        $this->pdo->beginTransaction();
        try {
            // ... the atomic invoice + line-items writes from the previous section ...
            $this->pdo->commit();
        } catch (\Throwable $e) {
            $this->pdo->rollBack();
            throw $e;
        }
    }

    public function find(string $number): ?Invoice
    {
        $stmt = $this->pdo->prepare('SELECT number, status, note FROM invoices WHERE number = :number');
        $stmt->execute(['number' => $number]);
        $row = $stmt->fetch();
        if ($row === false) {
            return null;
        }
        $lines = $this->pdo->prepare('SELECT description, cents FROM line_items WHERE invoice_number = :number');
        $lines->execute(['number' => $number]);
        return hydrateInvoice($row, $lines->fetchAll());
    }
}
Best practice: depend on the interface, construct the implementation once

Type-hint InvoiceRepository in your controllers and services, and build the one PdoInvoiceRepository (with its PDO connection) at the edge of the application, where the framework's container (Chapter 12, Chapter 13) wires it in. The payoff is the testability from Chapter 6: a unit test swaps in a trivial array-backed repository and never touches a database, while an integration test points the same code at an in-memory SQLite database for a real round-trip.

7.6 Schema as Versioned Code: Migrations

The database schema is part of the application, and it must travel with the code, not be edited by hand on a live server where the change is unrecorded and unrepeatable. A migration is a single, ordered, version-controlled change to the schema: create a table, add a column, add an index. A small runner applies pending migrations in order and records which have run in a migrations table, so every environment converges on the same structure from the same history. The first migration for the Ledger creates the two tables the repository above expects.

-- migrations/2026_06_01_000001_create_invoices.sql
CREATE TABLE invoices (
    number  VARCHAR(16) PRIMARY KEY,
    status  VARCHAR(16) NOT NULL,
    note    TEXT NULL
);
CREATE TABLE line_items (
    id              INTEGER PRIMARY KEY,
    invoice_number  VARCHAR(16) NOT NULL REFERENCES invoices(number),
    description     VARCHAR(255) NOT NULL,
    cents           INTEGER NOT NULL
);

You can write the runner yourself for a tiny project, but in practice you adopt a tool: Doctrine Migrations or Phinx as standalone packages, or the framework's own system (Laravel's migrations, Symfony through Doctrine), which is the route the framework chapters in Part IV take. The mechanism matters less than the discipline.

Caution: migrations run on deploy, and destructive ones need a plan

Applying migrations is a deployment step, run as part of the release rather than improvised over a production shell, and it pairs with the OPcache reset and atomic release swap from Section 22.1. Treat a migration that drops or rewrites data as you would any irreversible change: review it, back up first, and prefer an expand-then-contract sequence (add the new column and backfill in one release, remove the old one in a later release) so a rollback never has to recover data the migration already destroyed.

Lab 5 · Give the Ledger a transactional repository

Goal: build the PDO data layer behind the existing interface, prove the transaction is atomic, and round-trip a domain object through the database.

  1. Write the migration above and a few-line runner (or use SQLite directly for the lab) to create the invoices and line_items tables in a file-backed SQLite database under var/.
  2. Implement PdoInvoiceRepository behind the InvoiceRepository interface from Section 4.3, with the production PDO options and the transactional save() from this chapter.
  3. Prove atomicity: deliberately throw between the invoice insert and the line-item inserts, call save(), and confirm that neither the invoice nor any line survives (the rollback worked). Remove the forced failure and confirm a clean save persists everything.
  4. Implement find() with explicit hydration into Invoice, LineItem, and Money; confirm a saved invoice reads back as equal typed objects, and that a row with a negative cents value is rejected by the Money constructor rather than loaded silently.
  5. Add a PHPUnit test (Chapter 6) that runs against an in-memory SQLite database (sqlite::memory:) so the suite stays fast and needs no external server.
Exercise 7.1

Explain, in terms of the four ACID properties, exactly which one a transaction provides when it prevents an invoice from being saved without its line items. Then explain why hydrating a row through the Money constructor (rather than PDO's FETCH_CLASS, which by default assigns the column values before the constructor can validate them) is what keeps a corrupt or out-of-range value in the database from becoming an invalid object in your running code.

Part III Security

PHP sits at the most exposed point of an application: it is the code that runs attacker-supplied input on every request. This part treats security as a first-class engineering concern rather than a checklist bolted on at the end. Chapter 8 builds a PHP-specific threat model from the OWASP Top 10:2025. Chapter 9 covers the input and output handling that defeats injection and cross-site scripting, the two failure modes PHP is historically infamous for. Chapter 10 covers authentication, sessions, and cryptography using the modern primitives that make the old mistakes impossible. Chapter 11 hardens the runtime itself, explaining every php.ini directive that matters and why it is set the way it is.

Chapter 8The PHP Threat Model and the OWASP Top 10

Security is not a feature you add; it is a property of how you handle untrusted data at every boundary.

This chapter establishes the mindset and the map. The mindset is that all input is hostile until proven otherwise. The map is the OWASP Top 10:2025, the industry-consensus list of the most critical web application risks, translated into the specific forms each one takes in PHP and the chapter where this guide addresses it.

8.1 Why PHP Is Exposed

PHP's job is to receive an HTTP request, much of which is under the control of whoever sent it, and turn it into a response, often after touching a database, the filesystem, or another service. Every one of those steps crosses a trust boundary. The query string, the request body, headers, cookies, and uploaded files are all attacker-controllable. The historical PHP vulnerabilities were not the language being uniquely insecure; they were unsafe defaults (now removed) combined with a low barrier to entry that put many beginners directly in front of that boundary. The defenses are well understood and, in modern PHP and its frameworks, largely built in. Your job is to use them consistently.

8.2 The OWASP Top 10:2025, Mapped to PHP

Standard · OWASP Top 10:2025

The OWASP Top 10 is the industry-standard awareness document for web application security risks, representing a broad consensus drawn from analysis of hundreds of Common Weakness Enumerations across real applications. The 2025 edition is the eighth and current release. It reorders and reframes the list around root causes: Broken Access Control remains the top risk, Security Misconfiguration rises to second, Mishandling of Exceptional Conditions (A10) is a genuinely new category, and Software Supply Chain Failures (A03) expands and reframes the former Vulnerable and Outdated Components to cover the entire supply chain. Server-Side Request Forgery is now folded into Broken Access Control.OWASP Top 10:2025 (owasp.org/Top10/2025). The Top 10 is an awareness document, not a certification standard; for verifiable security requirements OWASP publishes the Application Security Verification Standard (ASVS) 5.0, used in Chapter 28.

OWASP Top 10:2025 categories, how each appears in PHP, and where this guide addresses it.
2025 categoryHow it appears in PHPWhere addressed
A01 Broken Access Control (now includes SSRF)Missing authorization checks; insecure direct object references (an invoice ID in the URL with no owner check); CSRF; server-side requests to attacker-chosen URLs.9.4, 9.5, frameworks 12/13
A02 Security MisconfigurationCode in the web root; display_errors on; default credentials; expose_php; permissive CORS; missing security headers.11, 20
A03 Software Supply Chain FailuresVulnerable or compromised Composer dependencies; unpinned versions; composer update in production; unverified packages.8.3, 3.2
A04 Cryptographic FailuresPlaintext or weak password hashes (md5, sha1); home-grown crypto; secrets in code; missing TLS.10
A05 InjectionSQL injection from string-built queries; cross-site scripting from unencoded output; command and LDAP injection.9.2, 9.3, 9.5
A06 Insecure DesignMissing rate limiting on login; no business-logic limits; trusting client-side checks; unsafe defaults baked into architecture.10, frameworks
A07 Authentication FailuresWeak password handling; session fixation; predictable session IDs; no multi-factor; credential stuffing.10
A08 Software or Data Integrity FailuresInsecure deserialization (unserialize() on user input); unsigned auto-updates; untrusted CI artifacts.9.6, 8.3
A09 Security Logging and Alerting FailuresNo audit log of security events; logs not centralized or tamper-evident; sensitive data written to logs.6.2, 25
A10 Mishandling of Exceptional ConditionsStack traces shown to users; fail-open error handling; unhandled exceptions leaking data or leaving inconsistent state.6.1, 11

Read this table as the spine of the next three chapters. Every defense that follows maps back to one or more of these categories, and the compliance crosswalk in Chapter 28 closes the loop by mapping them to the verifiable requirements of OWASP ASVS 5.0.

8.3 The Supply Chain Is Part of Your Threat Model

A03's promotion to its own category in 2025 reflects a real shift: most of the code in a PHP application is not yours, it is your Composer dependencies and their transitive dependencies. A compromised or vulnerable package runs with your application's full privileges. The defenses are concrete. Commit composer.lock and deploy with composer install (never update) so you ship exactly what you tested. Run composer audit, which checks your locked versions against a known-vulnerability database, in continuous integration. Minimize dependencies, and prefer well-maintained packages. Treat a dependency update as a code change that goes through review and tests, not a routine you automate blindly.

Best practice: make composer audit a build gate

Add composer audit to the check script and the CI pipeline so a newly disclosed vulnerability in a pinned dependency fails the build and prompts a deliberate upgrade. This turns supply-chain risk from something you discover after a breach into something the build tells you about the morning it is disclosed.

8.4 Trust Boundaries and Defense in Depth

The organizing principle for the rest of this part is the trust boundary: the line between data you control and data you do not. In PHP the inbound boundary is the superglobals ($_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, and the raw request body). The principle is that data crossing inward is validated before use, and data crossing outward (into SQL, into HTML, into a shell, into a log) is encoded for the destination it is entering. These are two different operations for two different boundaries, and conflating them is the source of much confusion: you validate input for what it should be, and you encode output for where it is going. Defense in depth means you do both, plus a hardened runtime and a confined process, so that a failure at one layer is contained by the next.

Exercise 8.1

For each of these Ledger features, name the most relevant OWASP 2025 category: (a) viewing an invoice by its numeric ID in the URL; (b) rendering a customer-supplied invoice note as HTML; (c) importing line items from an uploaded CSV; (d) the login form. Then state, for each, whether the defense is primarily input validation, output encoding, access control, or authentication. Check your answers against the table in Section 8.2.

Chapter 9Handling Input and Output Safely

This chapter is the practical core of PHP security: how to take untrusted input without being exploited, and how to emit output without becoming an attack vector for someone else.

The two dominant injection classes, SQL injection and cross-site scripting, are both solved completely by a single discipline applied consistently: parameterize queries, and encode output for its context. Everything here is demonstrated on the Grimoire Ledger.

9.1 Input: Validate, Do Not Trust

Request data arrives in the superglobals. Never use it raw. The modern approach is to validate that input matches what you expect (a positive integer, a well-formed email, a known enum value) and reject what does not, rather than trying to "clean" bad input into something usable, which is a losing game. PHP's filter_var validates and the frameworks in Part IV provide rich validators, but the principle is the same everywhere.

<?php
declare(strict_types=1);

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 1],
]);
if ($id === false || $id === null) {
    http_response_code(400);
    exit('Invalid invoice id.');
}
// $id is now guaranteed to be a positive int; use it with confidence
Best practice: validate for type and shape at the boundary, then work with typed values

Convert untrusted strings into validated, typed values (an int, an enum case, a value object) as early as possible, at the controller boundary. Past that point the rest of your code works with trustworthy types and does not need to re-check. This is why the typed domain from Chapter 4 is a security tool as much as a design one: a function that accepts InvoiceStatus cannot receive a malicious string.

9.2 SQL Injection and Prepared Statements

SQL injection happens when user input is concatenated into a query string, letting an attacker change the query's meaning. The fix is absolute and non-negotiable: never build SQL by string concatenation with user data. Use prepared statements, where the query structure is sent to the database first with typed placeholders, and the data is sent separately and can never be interpreted as SQL. PHP's database abstraction is PDO, and it supports this directly.

Standard · OWASP: prepared statements are the primary SQL injection defense

The OWASP SQL Injection Prevention Cheat Sheet names parameterized queries (prepared statements with bound parameters) as the first and primary defense, because they force a separation between code (the query) and data (the parameters) that the database enforces regardless of the input's content. Stored procedures and allow-list input validation are secondary defenses; escaping is a last resort that is error-prone and discouraged. This maps to OWASP Top 10:2025 A05, Injection.OWASP Cheat Sheet Series, "SQL Injection Prevention." The same guidance appears in the PHP Manual's PDO documentation and database security chapter. Use bound parameters for every value; never interpolate user data into a query string.

// the vulnerable pattern -- NEVER do this
$sql = "SELECT * FROM invoices WHERE number = '" . $_GET['number'] . "'";

// the correct pattern: a prepared statement with a bound parameter
$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,  // throw on error
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,  // use real server-side prepares
]);

$stmt = $pdo->prepare('SELECT * FROM invoices WHERE number = :number');
$stmt->execute(['number' => $number]);
$invoice = $stmt->fetch();

The three PDO options shown are the correct production defaults. Exception error mode means a database error throws rather than returning a value you might forget to check. Disabling emulated prepares means PDO uses the database's real prepared-statement protocol, which is both safer and gives correct types. With this pattern, the content of $number is irrelevant to the query's structure; an attacker can send ' OR 1=1 -- and it is treated as a literal invoice number that does not exist.

9.3 Cross-Site Scripting and Output Encoding

Cross-site scripting (XSS) is the output-side twin of injection: user data emitted into an HTML page without encoding, so that a value like <script>...</script> becomes executable code in another user's browser. The defense is context-aware output encoding: convert characters that are special in the destination context into their safe representations at the moment of output. For HTML body and attribute context, that is htmlspecialchars with the correct flags.

<?php
function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
?>
<p>Note: <?= e($invoice->note) ?></p>
<input value="<?= e($invoice->number) ?>">
Standard · OWASP: encode output for its context

The OWASP Cross-Site Scripting Prevention Cheat Sheet specifies that untrusted data must be encoded for the exact context in which it is placed (HTML body, HTML attribute, JavaScript, URL, CSS), because the rules differ per context. For the common HTML cases, encode with an entity-encoding function configured to encode quotes and using an explicit UTF-8 charset (ENT_QUOTES | ENT_HTML5). Modern template engines (Twig in Symfony, Blade in Laravel) auto-encode by default, which is why frameworks largely eliminate XSS when their escaping is not bypassed.OWASP Cheat Sheet Series, "Cross-Site Scripting Prevention." Maps to OWASP Top 10:2025 A05, Injection. Pass ENT_QUOTES and an explicit charset so the encoding never depends on a version's default flag set; the default flags became ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 only in PHP 8.1, so being explicit is both portable and self-documenting.

Caution: auto-escaping templates can be bypassed, and that is where XSS returns

Blade's {!! $raw !!} and Twig's |raw filter deliberately disable escaping. Every use of them is a place where XSS can re-enter, and every one should be justified and reviewed. The safe default is the escaping syntax ({{ $value }} in both engines); reach for raw output only for content you have separately sanitized with a dedicated HTML sanitizer, never for user input passed through directly.

9.4 Cross-Site Request Forgery

CSRF tricks an authenticated user's browser into making a state-changing request the user did not intend, by exploiting that browsers attach cookies automatically. The standard defense is a synchronizer token: a secret, per-session, unpredictable value embedded in every state-changing form and verified on submission, plus setting session cookies to SameSite=Lax or Strict so the browser does not send them on cross-site requests. Both frameworks generate and verify CSRF tokens automatically; when writing without a framework you implement the pattern yourself.

<?php
// issue a token (stored in the session) and embed it in the form
$token = bin2hex(random_bytes(32));
$_SESSION['csrf'] = $token;
?>
<form method="post" action="/invoices">
  <input type="hidden" name="csrf" value="<?= e($token) ?>">
  ...
</form>
<?php
// verify on submission with a timing-safe comparison
if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    http_response_code(403);
    exit('CSRF token mismatch.');
}

Two details matter. The token comes from random_bytes (cryptographically secure), not rand or uniqid. The comparison uses hash_equals, a constant-time comparison that does not leak how many leading characters matched through timing. CSRF maps to OWASP A01:2025, Broken Access Control, because it is fundamentally an authorization failure: the server acted on a request whose intent it did not actually verify.

9.5 The Other Injections: Command, Path, and SSRF

The same "data becomes code" pattern appears at other boundaries. Command injection occurs when user input reaches a shell via exec, shell_exec, or system; avoid shelling out at all where possible, and when unavoidable pass arguments through escapeshellarg and never build a command string from raw input. Path traversal occurs when user input chooses a filename and an attacker supplies ../../etc/passwd; validate against an allow-list of permitted names and resolve with realpath, confirming the result is inside the intended directory. Server-side request forgery (now part of A01) occurs when your server fetches a URL the user supplied, letting them reach internal services; validate the target against an allow-list of hosts and protocols and refuse internal address ranges.

<?php
// path traversal defense: confine to a known base directory
$base = '/srv/ledger/exports';
$name = $_GET['file'] ?? '';
if (!is_string($name) || $name === '') {
    http_response_code(400);
    exit('Invalid file.');
}
$requested = realpath($base . '/' . basename($name));
if ($requested === false || !str_starts_with($requested, $base . '/')) {
    http_response_code(404);
    exit('Not found.');
}
readfile($requested);

9.6 Insecure Deserialization

PHP's unserialize() reconstructs arbitrary objects from a string, and running it on attacker-controlled data can trigger "object injection" attacks, where the act of constructing or destructing crafted objects executes code. The rule is simple: never call unserialize() on untrusted input. For data interchange, use JSON (json_encode/json_decode), which produces only arrays and scalars and cannot instantiate objects. This maps to OWASP A08:2025, Software or Data Integrity Failures.

Standard · PHP Manual: do not unserialize untrusted data

The PHP Manual's unserialize() documentation warns explicitly that passing untrusted user input to unserialize() is unsafe regardless of options, because object instantiation and autoloading can be triggered, enabling code execution or injection. It recommends JSON for interchange of untrusted data. If a legacy format requires PHP serialization, the allowed_classes option limits which classes may be instantiated, but JSON remains the correct choice for any new design.php.net, function reference for unserialize, security warning. Maps to OWASP Top 10:2025 A08, Software or Data Integrity Failures.

9.7 Handling File Uploads Safely

The Ledger imports line items from an uploaded CSV, which means it accepts a file an attacker fully controls. Three rules keep that safe. First, confirm the file actually arrived as a PHP upload with is_uploaded_file() and move it with move_uploaded_file() rather than trusting a path. Second, never trust the client-supplied name or MIME type ($_FILES[...]['name'] and ['type'] are attacker-controlled): determine the type yourself by inspecting the bytes, and validate the data by actually parsing it. Third, store the file outside the web root under a name you generate, so it can never be requested back as a URL or executed (the FastCGI rules in Section 20.2 are the second layer of that defense).

<?php
declare(strict_types=1);

$f = $_FILES['import'] ?? null;
if ($f === null || $f['error'] !== UPLOAD_ERR_OK || !is_uploaded_file($f['tmp_name'])) {
    http_response_code(400);
    exit('Upload failed.');
}
// verify the type by inspection, not by the client-sent ['type']
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($f['tmp_name']);
if (!in_array($mime, ['text/csv', 'text/plain'], true)) {
    http_response_code(415);
    exit('Only CSV is accepted.');
}
// store outside the web root under a generated name
$dest = '/srv/ledger/imports/' . bin2hex(random_bytes(16)) . '.csv';
move_uploaded_file($f['tmp_name'], $dest);
Caution: a content-type check is necessary, not sufficient

Inspecting the bytes beats trusting the browser, but a file can be valid CSV and still hostile: a "CSV injection" payload (a cell beginning with =, +, -, or @) can execute as a formula if the data is later opened in a spreadsheet. Validate each parsed row against the types you expect (a description string, an integer number of cents) and neutralize risky leading characters when you re-export. The rule from Section 9.1 holds: validate for the shape you want, then work with typed values.

Lab 6 · Give the Ledger a safe database layer

Goal: take the data layer you built in Chapter 7 and prove it is injection-resistant, add output encoding and CSRF protection, then attempt the classic attacks and watch them fail.

  1. Use the PdoInvoiceRepository from Chapter 7 against a local database (SQLite is enough for the lab; PostgreSQL or MySQL for realism), and add an invoice-lookup query that takes the number from request input.
  2. Confirm the connection uses the three production options from Section 9.2 (exception error mode, emulation off) and that every query binds its parameters rather than concatenating them, the discipline this chapter explains and Chapter 7 implements.
  3. Add a view that prints an invoice note through the e() helper from Section 9.3.
  4. Attack your own app: request an invoice with number set to ' OR '1'='1 and confirm it matches nothing. Save an invoice note of <script>alert(1)</script> and confirm it renders as inert text, not a running script.
  5. Add a CSRF token to the "create invoice" form and verify it with hash_equals; confirm a POST without the token is rejected with 403.
Exercise 9.1

Explain why prepared statements stop SQL injection even when the user input contains valid SQL syntax, in terms of the separation between the query and its parameters. Then explain why output encoding, not input filtering, is the correct defense for XSS (hint: the same stored note is safe in a JSON API response and dangerous in an HTML page; what does that tell you about where the defense belongs?).

Chapter 10Authentication, Sessions & Cryptography

Authentication and the cryptography under it are where small mistakes become total compromises, and where PHP's modern primitives make the right thing the easy thing.

This chapter covers password storage, session security, cryptography, and the request-layer defenses that protect the login itself, using the functions you should use and the legacy ones you must never use again. The throughline is: use the high-level primitive the language provides, and never invent your own.

10.1 Password Storage

Passwords are never stored, and never encrypted; they are hashed with a slow, salted, purpose-built algorithm so that even a full database breach does not reveal them. PHP provides exactly two functions you need, and they handle salting, algorithm selection, and cost automatically.

Standard · OWASP and the PHP Manual: hash passwords with password_hash

The OWASP Password Storage Cheat Sheet recommends a memory-hard algorithm (Argon2id) or, where unavailable, bcrypt, with appropriate cost parameters, applied to a unique per-password salt. PHP's password_hash() implements exactly this: it generates a cryptographically secure random salt, applies the selected algorithm (PASSWORD_BCRYPT or PASSWORD_ARGON2ID), and encodes the algorithm and parameters into the output so password_verify() can check a candidate with no separate salt handling. The default PASSWORD_DEFAULT tracks the current recommended algorithm across PHP versions; as of PHP 8.4 that default is still bcrypt, so pass PASSWORD_ARGON2ID explicitly when you want the memory-hard algorithm OWASP lists first.OWASP Cheat Sheet Series, "Password Storage"; php.net function reference for password_hash and password_verify. Maps to OWASP Top 10:2025 A04 (Cryptographic Failures) and A07 (Authentication Failures). Never use md5, sha1, or any fast or unsalted hash for passwords.

<?php
// at registration: hash and store the result string (about 60-100 chars)
$hash = password_hash($plaintextPassword, PASSWORD_DEFAULT);

// at login: verify against the stored hash
if (password_verify($candidate, $hash)) {
    // transparently upgrade the hash if the default cost/algorithm has moved on
    if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
        $hash = password_hash($candidate, PASSWORD_DEFAULT);
        $repository->updatePasswordHash($userId, $hash);
    }
    // establish the authenticated session (see 10.2)
} else {
    // generic failure message; do not reveal whether the user exists
}

The password_needs_rehash step is what keeps stored hashes current: when you raise the cost or PHP advances PASSWORD_DEFAULT, each user's hash is upgraded the next time they log in, with no migration script and no mass reset.

10.2 Sessions

HTTP is stateless, so "this is the same logged-in user as the previous request" is tracked by a session: PHP issues a random session ID in a cookie, and stores the associated data server-side. The security of authentication rests on the session ID being unpredictable, confidential in transit, and rotated at the right moments. The two attacks to defeat are session fixation (an attacker sets a known session ID before login) and session hijacking (an attacker steals the ID). The defenses are to regenerate the ID at every privilege change and to lock down the cookie.

<?php
// the cookie parameters that protect the session ID (set before session_start)
session_set_cookie_params([
    'lifetime' => 0,  // session cookie, gone when the browser closes
    'path'     => '/',
    'secure'   => true,  // only sent over HTTPS
    'httponly' => true,  // not readable by JavaScript (limits XSS theft)
    'samesite' => 'Lax',  // not sent on cross-site requests (CSRF defense)
]);
session_start();

// on successful login, regenerate the ID to defeat fixation
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
Best practice: regenerate on every privilege boundary

Call session_regenerate_id(true) immediately after login, after any privilege elevation, and consider it after logout (followed by destroying the session). The argument true deletes the old session file so a captured old ID is useless. Combined with session.use_strict_mode (set in Chapter 11), which makes PHP reject a client-supplied session ID it never issued, this closes session fixation entirely.

These cookie flags can be set per call as above, or, better, enforced globally in php.ini so every session inherits them and no code can forget. Section 11.6 sets them there.

10.3 Cryptography: Use libsodium, Never Roll Your Own

When you need to encrypt data, sign it, or generate secure randomness, use the high-level primitives PHP bundles, and never assemble your own scheme from low-level pieces. Modern PHP includes libsodium (the sodium_* functions) in core: authenticated encryption, public-key cryptography, and password hashing, with safe defaults and misuse-resistant APIs. For random values, use random_bytes() and random_int(), which draw from the operating system's cryptographically secure generator.

Standard · PHP Manual: cryptographically secure randomness and Sodium

The PHP Manual specifies that random_bytes() and random_int() generate cryptographically secure pseudo-random values suitable for security contexts (tokens, keys, salts), unlike rand(), mt_rand(), or uniqid(), which are not secure and must never be used for security purposes. The Sodium extension (libsodium) is part of PHP core and provides authenticated encryption (sodium_crypto_secretbox), public-key encryption, and signing with safe defaults.php.net, function references for random_bytes, random_int, and the Sodium extension. Maps to OWASP Top 10:2025 A04, Cryptographic Failures. The guidance is uniform across OWASP and the PHP Manual: use vetted high-level primitives, never custom constructions.

<?php
// authenticated symmetric encryption with libsodium
$key   = sodium_crypto_secretbox_keygen();  // 32-byte key; store securely
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);  // unique per message
$cipher = sodium_crypto_secretbox($plaintext, $nonce, $key);

$plain = sodium_crypto_secretbox_open($cipher, $nonce, $key);
if ($plain === false) {
    throw new \RuntimeException('Decryption failed or message was tampered with.');
}

10.4 Secrets Management

Keys, database passwords, and API tokens are configuration, not code, and must never be committed to the repository. The convention is to read them from the environment (the $_ENV/getenv mechanism, populated from a .env file in development that is git-ignored, and from real environment variables or a secrets manager in production). Both frameworks formalize this with a .env file and a typed config layer. The cardinal rule, which maps to OWASP A04, is that a secret never appears in source control, in a log, or in an error page.

Caution: a committed secret is a compromised secret

Once a credential is pushed to a repository it must be treated as exposed and rotated, even in a private repo, because it persists in history and in every clone. Keep .env in .gitignore from the first commit, scan for accidentally committed secrets in CI, and store production secrets in the platform's secret store rather than in any file inside the deployment.

10.5 Throttling, Lockout, and Multi-Factor

Strong password hashing protects stored credentials, but it does nothing to stop an attacker from trying millions of guesses against the login form. Two of the A07:2025 risks named in Chapter 8, credential stuffing and brute force, are defeated at the request layer rather than in the hash. Rate-limit authentication attempts per account and per source address with an increasing backoff, and lock the account or step up verification after a threshold of failures. Keep the response time and message identical whether or not the account exists, so the endpoint does not become a username oracle. For anything sensitive, offer multi-factor authentication (a TOTP authenticator app or a WebAuthn/passkey credential), which makes a stolen password insufficient on its own.

Best practice: let the framework rate-limit the login

Do not hand-roll throttling. Laravel's throttle middleware and its built-in login rate limiter, and Symfony's RateLimiter component wired into the security firewall, both implement per-key limits with backoff and lockout that you configure rather than write. Apply them to the login, password-reset, and token endpoints, and record lockout events to the security log (Section 6.2) so repeated failures are visible (OWASP A09:2025).

Exercise 10.1

A developer proposes storing passwords with hash('sha256', $password) "because SHA-256 is a strong, modern hash." Explain why this is wrong for passwords despite SHA-256 being cryptographically strong (hint: what property do you actually want from a password hash, and is "fast" one of them?). What two PHP functions do it correctly, and what do they handle that the SHA-256 approach does not?

Chapter 11Hardening the Runtime: php.ini Explained

The application can be perfect and still be undone by a permissive runtime.

This chapter hardens PHP itself by explaining, directive by directive, the php.ini settings that matter for security, why each one is set the way it is, and how the settings differ between the FPM and CLI runtimes. The goal is not a config file to paste blindly (that is in Appendix A) but an understanding deep enough to defend each value to an auditor.

11.1 Where Configuration Lives, and the FPM/CLI Split

PHP reads a main php.ini, then files in a conf.d directory, and the set it reads depends on the SAPI. The CLI and FPM load different php.ini files, which is the single most common configuration surprise: a setting you changed for the command line has no effect on the web application. Always confirm which file FPM uses. Beyond the ini files, FPM pools can override settings per pool with php_value and php_admin_value (the "admin" form cannot be overridden at runtime by the application), which is how you give different sites different limits, covered in Chapter 19.

$ php --ini  # the CLI's files
# php-fpm -i | grep 'php.ini'  # RHEL/Fedora binary name; on Debian/Ubuntu it is php-fpm8.4
# Debian/Ubuntu: /etc/php/8.4/fpm/php.ini and /etc/php/8.4/fpm/conf.d/
# RHEL/Fedora:   /etc/php.ini and /etc/php.d/, with FPM pools in /etc/php-fpm.d/

11.2 Error Handling: Log Everything, Display Nothing

The most important security setting in php.ini is also the simplest: in production, errors are logged, never displayed. A displayed error or stack trace hands an attacker a map of your filesystem and code, and sometimes credentials embedded in a query. This directly addresses OWASP A10:2025 (Mishandling of Exceptional Conditions) and A02 (Security Misconfiguration).

Error-handling directives and their production values, with the reason for each.
DirectiveProduction valueWhy
display_errorsOffNever show errors to clients; they leak paths, code, and data.
display_startup_errorsOffStartup errors leak the same information before your handler runs.
log_errorsOnCapture every error to a log you can investigate.
error_log/var/log/php/error.log or syslogSend logs to a controlled, rotated destination (or stderr in containers).
error_reportingE_ALLReport everything to the log, including deprecations, so problems surface early.

In development you invert the first two (display_errors = On) so you see failures instantly. That is the only difference, and it is why the two environments must use different ini files or environment-driven configuration. Never copy a development ini to production.

11.3 Hiding PHP and Reducing the Attack Surface

Two settings reduce what an attacker learns and what dangerous machinery is available. expose_php = Off removes the X-Powered-By: PHP/8.4.x response header, so version-specific automated attacks have less to target. This is a small but standard hardening step (the web-server layer that strips other identifying headers is in Chapter 20).

Standard · OWASP PHP Configuration Cheat Sheet

The OWASP PHP Configuration Cheat Sheet provides the consensus baseline for hardening php.ini. Its core recommendations include disabling display_errors and expose_php in production, enabling log_errors, restricting filesystem access with open_basedir, setting conservative resource limits (memory_limit, max_execution_time, post_max_size, upload_max_filesize), hardening the session cookie directives, and disabling rarely needed dangerous functions. There is no DISA STIG or CIS Benchmark for PHP itself, so this cheat sheet and the PHP Manual's security chapter are the authoritative baselines this guide follows.OWASP Cheat Sheet Series, "PHP Configuration"; php.net Manual, "Security" chapter. The absence of a formal PHP benchmark is stated plainly in Chapter 28; where a control needs a benchmark, the closest applicable ones are the CIS Linux, web server, and Docker benchmarks applied to the surrounding stack.

11.4 Resource Limits

Resource limits are both a stability and a security control: they bound what a single request, including a malicious one, can consume, and they cap the impact of a denial-of-service attempt. Set them deliberately to the application's real needs rather than leaving generous defaults.

Resource-limiting directives. Tune to the application; these are conservative starting points.
DirectiveStarting valueWhy
memory_limit128MCaps per-request memory so one request cannot exhaust the host. Raise only for measured needs.
max_execution_time30Kills runaway requests. Under FPM, pair with the pool's request_terminate_timeout.
post_max_size8MCaps request body size; must be at least upload_max_filesize.
upload_max_filesize2MCaps individual uploaded file size. Raise only if the app genuinely accepts larger files.
max_input_vars1000Limits the number of input variables to blunt hash-collision and oversized-form attacks.

11.5 Disabling Dangerous Features

A few language features are powerful enough to turn a minor vulnerability into a full compromise, and most applications never need them. allow_url_fopen and especially allow_url_include let file functions reach across the network; allow_url_include should always be Off (it enables remote code inclusion and is off by default for good reason), and allow_url_fopen can often be Off if you use an HTTP client instead of file functions for remote URLs. The disable_functions directive removes named functions entirely from the runtime; disabling the shell-execution family on a server that never shells out closes the command-injection avenue at the engine level. The list below also disables curl_multi_exec, which is not a shell function but lets a compromised application open outbound network connections (useful to an attacker for server-side request forgery, data exfiltration, or fetching a second-stage payload), so it is removed too where the application does not need parallel cURL.

; harden the runtime against the most abused features (in php.ini)
allow_url_include = Off
allow_url_fopen   = Off          ; if the app does not fetch remote URLs via file functions
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_multi_exec
enable_dl         = Off          ; forbid loading extensions at runtime
Caution: disable_functions is a blunt instrument, test it

disable_functions is a defense-in-depth measure, not a substitute for not calling those functions. Disabling a function your application or a dependency legitimately uses will break it at runtime, so verify against your real dependency tree before applying it in production. It is a hardening layer for the case where an attacker reaches code execution, not a primary control, and it does not replace mandatory access control confinement of the FPM process (the subject of the SELinux companion volume, and of AppArmor on the Debian/Ubuntu family).

11.6 Session Hardening in php.ini

The session cookie flags from Section 10.2 are best set globally so every session inherits them and no code can forget. These directives, set in php.ini, are the runtime backbone of session security.

; session security baseline (php.ini)
session.cookie_secure   = On      ; cookie only over HTTPS
session.cookie_httponly = On      ; cookie not readable by JavaScript
session.cookie_samesite = Lax     ; cookie not sent on cross-site requests
session.use_strict_mode = On      ; reject session IDs PHP did not issue (anti-fixation)
session.use_only_cookies = On     ; never accept a session ID from the URL

Two older hardening directives are deliberately absent. PHP 8.4 deprecates session.sid_length and session.sid_bits_per_character, and the default 32-character hexadecimal session ID already carries 128 bits of entropy, so leave both at their defaults rather than lengthening the ID (php.net Manual, "Migrating from PHP 8.3.x to PHP 8.4.x," Deprecated Features).

Together with session_regenerate_id(true) at login, these settings make session fixation and hijacking substantially harder, and they do it for the whole application from one place. This is the configuration backing for the authentication work in Chapter 10, and it maps to OWASP A07:2025, Authentication Failures.

Lab 7 · Harden the Ledger's runtime

Goal: apply a production-grade hardened configuration to the FPM runtime and verify each control actually took effect.

  1. Find the FPM php.ini with php-fpm -i | grep 'Loaded Configuration' (on the Debian/Ubuntu family the binary is versioned: php-fpm8.4). Make a backup.
  2. Set the error directives from Section 11.2 for production (display_errors = Off, log_errors = On, a real error_log), and expose_php = Off.
  3. Apply the resource limits, the dangerous-feature settings, and the session directives. Reload FPM (systemctl reload php8.4-fpm or the RHEL-family service name).
  4. Verify: curl -sI https://localhost/ shows no X-Powered-By header; trigger an application error and confirm the browser shows a generic page while the detail appears in the error log; check a session cookie in the browser tools and confirm Secure, HttpOnly, and SameSite=Lax are set.
  5. Cross-check your settings against the OWASP PHP Configuration Cheat Sheet and note any your application's needs justify deviating from. The full annotated file is Appendix A.
Exercise 11.1

You set display_errors = Off in /etc/php.ini but errors still appear in the browser. List two reasons this can happen (hint: which file does FPM read, and can a framework or a .user.ini override the value?). What single command shows you the value PHP-FPM actually has loaded at runtime?

Part IV Frameworks

Almost no production PHP is written without a framework, because a framework supplies the routing, dependency injection, database mapping, templating, validation, and security machinery you would otherwise build and maintain yourself, much of it the exact defenses Part III described. Two frameworks dominate, and they embody different philosophies. Chapter 12 covers Laravel, which optimizes for developer velocity and convention. Chapter 13 covers Symfony, which optimizes for explicit, decoupled, reusable components. Chapter 14 steps back to help you choose deliberately, including the microframeworks and the long-running runtimes that change the shared-nothing model from Section 1.3. Chapter 15 then builds an HTTP API for the Ledger on top of whichever framework you choose, using the standards that keep an API predictable for the programs that consume it.

Chapter 12Laravel in Depth

Laravel is the most widely used PHP framework, and its design goal is developer happiness through convention: sensible defaults, an expressive API, and batteries included for almost everything a web application needs.

This chapter covers how Laravel is structured, the request lifecycle through its service container and middleware, its Eloquent ORM and Blade templates, and the security features that make the Part III defenses automatic. The Grimoire Ledger is the worked example.

12.1 Philosophy and Shape

Laravel favors convention over configuration and a fluent, readable API. A new Laravel application arrives with routing, an ORM, a template engine, a queue system, a task scheduler, authentication scaffolding, a test harness, and a command-line tool already wired together. The trade-off is that Laravel has opinions, and working with them is fast while working against them is friction. For most web applications, especially product-style applications built by small teams under time pressure, that trade is strongly favorable.

Standard · Laravel release and support policy

Laravel ships a major version roughly once a year (early in the year). As of June 2026 the current release is Laravel 13 (released 17 March 2026), which requires PHP 8.3 or later. Laravel provides bug fixes for 18 months and security fixes for 2 years per release. New projects should target the current major on a supported PHP version; long-lived projects should budget for the annual upgrade, which Laravel has deliberately made low-friction (recent majors target zero or minimal breaking changes).laravel.com, "Release Notes" and support policy, retrieved June 2026. Laravel 13 requires PHP 8.3+. The framework leans on Symfony components underneath (HttpFoundation, Console, Routing, and others), so the two ecosystems are more related than they appear.

12.2 The Request Lifecycle: Container, Providers, Middleware

Every request enters through public/index.php (the front controller pattern from Section 3.6), which boots the application and resolves the HTTP kernel. The kernel sends the request through a middleware pipeline (each layer can inspect, modify, or reject the request and response: this is the PSR-15 model in spirit), then to a matched route, then to a controller. Two ideas make Laravel cohere. The service container is a dependency-injection container (a PSR-11 container) that constructs your classes and automatically supplies their typed dependencies. Service providers are the bootstrap units that register services into the container. You rarely touch the container directly; you type-hint a dependency in a constructor or controller method and Laravel injects it.

// a controller: dependencies are injected by type from the container
final class InvoiceController extends Controller
{
    public function __construct(private InvoiceRepository $invoices) {}

    public function show(string $number): Response
    {
        $invoice = $this->invoices->find($number) ?? abort(404);
        return response()->view('invoices.show', ['invoice' => $invoice]);
    }
}

12.3 Routing

Routes map a URL and HTTP method to a controller action, declared in routes/web.php (session-based, CSRF-protected web routes) and routes/api.php (stateless token routes). Route model binding can resolve a model from a URL parameter automatically.

// routes/web.php
use App\Http\Controllers\InvoiceController;

Route::get('/invoices/{number}', [InvoiceController::class, 'show']);
Route::post('/invoices', [InvoiceController::class, 'store'])->middleware('auth');

12.4 Eloquent: the Active Record ORM

Eloquent is Laravel's object-relational mapper, and it follows the Active Record pattern: each model class both represents a row and carries the methods to load and save it. This makes simple persistence extremely concise. Migrations define the schema in versioned PHP, so the database structure travels with the code.

// app/Models/Invoice.php
final class Invoice extends Model
{
    protected $fillable = ['number', 'status'];  // mass-assignment allow-list
    protected $casts = ['status' => InvoiceStatus::class]; // cast column to the enum

    public function lineItems(): HasMany
    {
        return $this->hasMany(LineItem::class);
    }
}

// usage reads like the domain
$invoice = Invoice::where('number', $number)->with('lineItems')->firstOrFail();
$invoice->status = InvoiceStatus::Paid;
$invoice->save();
Standard · Eloquent and mass-assignment protection (OWASP A01/A08)

Eloquent guards against mass-assignment vulnerabilities, where a request body sets model attributes the user should not control (for example flipping an is_admin column), through the $fillable allow-list (or $guarded block-list). Only listed attributes can be set from bulk input such as Invoice::create($request->all()). Leaving a model fully unguarded re-opens the vulnerability. Combined with Eloquent's use of PDO prepared statements for every query (so values are always parameterized, never interpolated), this addresses the injection and broken-access-control risks from Chapter 8 at the framework level.laravel.com, Eloquent "Mass Assignment" and the query builder's use of PDO bindings. Maps to OWASP Top 10:2025 A01 (Broken Access Control) and A05 (Injection). The protection is on by default; the foot-gun is disabling it.

12.5 Blade Templates and Automatic Escaping

Blade is Laravel's template engine. Its {{ $value }} syntax automatically encodes output with htmlspecialchars, making the XSS defense from Section 9.3 the default rather than a thing you must remember. The raw syntax {!! $value !!} bypasses escaping and is the one place XSS can re-enter, as cautioned earlier.

{{-- resources/views/invoices/show.blade.php --}}
<h1>Invoice {{ $invoice->number }}</h1>   {{-- auto-escaped --}}
<span>{{ $invoice->status->label() }}</span>
<form method="POST" action="/invoices/{{ $invoice->number }}/pay">
    @csrf                                  {{-- injects the CSRF token field --}}
    <button>Mark paid</button>
</form>

12.6 Validation

Laravel validates input declaratively, most cleanly through a Form Request class that both authorizes and validates before the controller runs, so the controller only ever sees valid data. This is the framework expression of "validate at the boundary" from Section 9.1.

final class StoreInvoiceRequest extends FormRequest
{
    public function authorize(): bool { return $this->user()->can('create', Invoice::class); }

    public function rules(): array
    {
        return [
            'number' => ['required', 'string', 'max:16', 'unique:invoices,number'],
            'lines'  => ['required', 'array', 'min:1'],
            'lines.*.cents' => ['required', 'integer', 'min:0'],
        ];
    }
}

12.7 Authentication, Authorization, and Built-in Security

Laravel ships authentication starter kits (with options for first-party or third-party identity), and an authorization layer of gates and policies that centralize "can this user do this action to this object." For APIs, Sanctum issues tokens and Passport provides full OAuth2. Underneath, Laravel uses password_hash/password_verify for credentials (Section 10.1), provides authenticated application-level encryption (OpenSSL AES-256-CBC with an HMAC) keyed from APP_KEY, and enables CSRF protection on web routes by default. In Laravel 13 the CSRF middleware was renamed to a request-forgery-protection middleware, but the behavior is the synchronizer-token pattern from Section 9.4, applied automatically.

// an authorization policy centralizes the access-control decision (OWASP A01)
final class InvoicePolicy
{
    public function update(User $user, Invoice $invoice): bool
    {
        return $user->id === $invoice->owner_id;  // owner-only; no IDOR
    }
}

12.8 The Operational Ecosystem

Artisan is Laravel's command-line tool (migrations, code generation, custom commands, queue workers). The queue system offloads slow work (email, PDF generation, the Ledger's invoice exports) to background workers, essential for scaling (Chapter 22). The scheduler replaces cron entries with code. For deployment, first-party tooling automates server provisioning and zero-downtime releases, and Octane runs the application on a long-running runtime (Swoole, RoadRunner, or FrankenPHP) for higher throughput, with the statefulness caveats covered in Section 14.5. For production, the framework caches its configuration, routes, and views into optimized files.

Best practice: run the production optimizers in your deploy

A Laravel deploy should run composer install --no-dev --optimize-autoloader and then the framework's caching commands (config cache, route cache, view cache, and event cache). These collapse configuration discovery and route registration into precomputed files, a measurable latency win on every request. Remember to clear and rebuild them on each deploy, and never cache config in local development, where you want changes to take effect immediately.

Exercise 12.1

Rebuild the Ledger's "show invoice" and "mark paid" features in a fresh Laravel application: a migration and Eloquent model for Invoice with a status cast to the InvoiceStatus enum, a controller, a Blade view, and a policy that allows only the owner to mark an invoice paid. Confirm three things happen without you writing them: output is auto-escaped, the form is CSRF-protected, and the query uses a prepared statement. Which Part III defense does each correspond to?

Note: testing a Laravel application

Laravel's own test tooling (feature tests, the RefreshDatabase trait, model factories, the HTTP test assertions, and the facade fakes) is covered in Section 17.4, building on the testing fundamentals of Chapter 16.

Chapter 13Symfony in Depth

Symfony is the other major framework, and it is also a foundation: its decoupled components are used far beyond Symfony applications, including inside Laravel, Drupal, and countless libraries.

Where Laravel optimizes for convention and speed of authorship, Symfony optimizes for explicitness, configurability, and reuse. This chapter covers Symfony's kernel and dependency-injection container, attribute-based routing, the Doctrine data-mapper ORM, Twig templates, and the Security component, building the same Ledger features so the contrast with Chapter 12 is direct.

13.1 Philosophy: Components and Explicitness

Symfony began as a set of independent components (HttpFoundation, Routing, Console, EventDispatcher, DependencyInjection, and more) and a framework that wires them together. Those components are deliberately usable on their own, which is why other projects depend on them and why learning Symfony teaches you reusable building blocks rather than a single monolith. Symfony favors explicit configuration and dependency injection over implicit convention, which makes large, long-lived, multi-team applications easier to reason about at the cost of more upfront ceremony than Laravel.

Standard · Symfony release and LTS policy

Symfony releases a minor version every six months (May and November) under a predictable calendar, and designates a Long-Term Support release every two years (the .4 of a major). As of June 2026 the current stable line is Symfony 8.1 (May 2026), and the active LTS is Symfony 7.4 (released November 2025; bug fixes for three years, security fixes for four), with Symfony 8.4 set to be the next LTS. Standard releases receive eight months of bug fixes and fourteen months of security fixes; LTS releases extend that substantially. Choose the current stable for greenfield work that will track upgrades, or the LTS for applications that need a long, stable support window.symfony.com, "Releases" and "The Release Process," retrieved June 2026. The six-month cadence and the .4-is-LTS rule make Symfony's upgrade planning unusually predictable, which is itself a reason large organizations choose it.

13.2 The Kernel, the Container, and Autowiring

A Symfony request flows through the HttpKernel: it turns a Request into a Response by dispatching events (so listeners can hook the lifecycle), resolving the controller for the route, and invoking it. The heart of the framework is its dependency-injection container with autowiring: you type-hint an interface or class in a constructor, and the container supplies the right service automatically, configured in config/services.yaml. Symfony's container is a superset of the PSR-11 contract and is more powerful (and more explicit) than the convention-driven resolution in Laravel.

// src/Controller/InvoiceController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Repository\InvoiceRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class InvoiceController extends AbstractController
{
    public function __construct(private InvoiceRepository $invoices) {}  // autowired

    #[Route('/invoices/{number}', name: 'invoice_show', methods: ['GET'])]
    public function show(string $number): Response
    {
        $invoice = $this->invoices->findOneBy(['number' => $number])
            ?? throw $this->createNotFoundException();
        return $this->render('invoice/show.html.twig', ['invoice' => $invoice]);
    }
}

Routing here is declared with the #[Route] attribute right on the action, the attribute mechanism from Section 4.6. Configuration that is not routing (services, security, framework options) lives in config/, typically as YAML, keeping wiring explicit and discoverable.

13.3 Doctrine: the Data-Mapper ORM

Symfony's standard ORM is Doctrine, and it follows the Data Mapper pattern, the key architectural contrast with Eloquent. Your entity is a plain object that knows nothing about the database; a separate entity manager and repositories handle persistence. This separation makes the domain model independent of storage (easier to test and to reason about in complex domains) at the cost of more moving parts than Active Record. Entities are mapped with attributes; the schema is evolved with versioned migrations. One deliberate departure from the final-by-default stance of Section 4.1: a Doctrine entity is left non-final, because Doctrine builds its lazy-loading proxies by subclassing the entity (PHP 8.4 native lazy objects, adopted by Doctrine ORM 3.4 and later, lift this constraint).

// src/Entity/Invoice.php
<?php
declare(strict_types=1);

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: \App\Repository\InvoiceRepository::class)]
class Invoice  // not final: Doctrine subclasses entities for lazy-loading proxies
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 16, unique: true)]
    private string $number;

    #[ORM\Column(enumType: InvoiceStatus::class)]
    private InvoiceStatus $status = InvoiceStatus::Draft;

    public function markPaid(): void { $this->status = InvoiceStatus::Paid; }
    // ... typed getters; the entity is a plain object, not a row
}

// persistence is explicit, via the entity manager
$invoice->markPaid();
$entityManager->flush();  // Doctrine writes the change with a prepared statement

Doctrine, like Eloquent, parameterizes every query through PDO, so the SQL injection defense is automatic. The difference from Eloquent is conceptual: with Doctrine you manipulate domain objects and the mapper figures out the SQL, rather than the model itself being the persistence API. Chapter 14 discusses which pattern suits which problem.

13.4 Twig, Forms, and Validation

Twig is Symfony's template engine, and like Blade it auto-escapes output by default, making XSS protection the standard behavior; the |raw filter is the explicit, reviewable bypass. The Form component builds, renders, and processes forms with CSRF protection built in, and the Validator component (using the constraint attributes from Section 4.6) validates objects declaratively.

{# templates/invoice/show.html.twig #}
<h1>Invoice {{ invoice.number }}</h1>          {# auto-escaped #}
<span>{{ invoice.status.label }}</span>
{{ form_start(payForm) }}{{ form_widget(payForm) }}{{ form_end(payForm) }}  {# CSRF token included #}
// validation via constraints on the object
use Symfony\Component\Validator\Constraints as Assert;

final class CreateInvoice
{
    #[Assert\NotBlank, Assert\Length(max: 16)]
    public string $number = '';

    #[Assert\Valid, Assert\Count(min: 1)]
    public array $lines = [];
}

13.5 The Security Component

Symfony's Security component handles authentication and authorization explicitly and flexibly: authenticators establish identity, password hashers wrap password_hash with per-algorithm configuration, and voters centralize authorization decisions (the analog of Laravel's policies). Access control can also be declared by firewall and route. This is the framework realization of Chapter 10, with the access-control decisions kept in one auditable place per OWASP A01.

// a voter centralizes an authorization decision
final class InvoiceVoter extends Voter
{
    protected function supports(string $attribute, mixed $subject): bool
    {
        return $attribute === 'INVOICE_EDIT' && $subject instanceof Invoice;
    }

    protected function voteOnAttribute(string $attr, mixed $subject, TokenInterface $token): bool
    {
        return $subject->getOwnerId() === $token->getUser()?->getId();
    }
}

// in the controller
$this->denyAccessUnlessGranted('INVOICE_EDIT', $invoice);

13.6 Console, Messenger, and Production

The Console component provides Symfony's command-line tooling, including the bin/console commands for cache, database, and debugging. The Messenger component is Symfony's message bus and queue system for asynchronous work, the analog of Laravel's queues and equally important for scaling. For production, Symfony runs in the prod environment with a warmed cache (cache:warmup), which precompiles the container and routes; running in dev in production is a serious misconfiguration that exposes the profiler and detailed errors.

Caution: never deploy Symfony in the dev environment

The Symfony dev environment enables the web profiler, verbose exceptions with stack traces, and the debug toolbar, all of which leak internal detail and are an OWASP A02 (Security Misconfiguration) and A10 (Mishandling of Exceptional Conditions) finding in production. Production runs with APP_ENV=prod, APP_DEBUG=0, and a warmed cache. Confirm this in your deployment exactly as you confirm display_errors = Off for plain PHP in Chapter 11.

Exercise 13.1

Build the Ledger's invoice in Symfony as a Doctrine entity with an InvoiceStatus enum column, an attribute-routed controller, a Twig view, and an InvoiceVoter that allows only the owner to edit. Compare the result to the Laravel version from Exercise 12.1: where did Eloquent's Active Record make the code shorter, and where did Doctrine's Data Mapper keep the domain object cleaner? You will use this comparison to answer the choice question in Chapter 14.

Note: testing a Symfony application

Symfony's own test tooling (KernelTestCase and WebTestCase, the test client, the service container, the PHPUnit Bridge, and the transactional test bundle) is covered in Section 17.5, building on the testing fundamentals of Chapter 16.

Chapter 14Choosing a Framework: Laravel, Symfony & the Microframeworks

Having built the same application twice, you can now choose deliberately.

This chapter names the real decision axes, including the Active Record versus Data Mapper question that sits underneath the Laravel/Symfony choice, surveys the microframeworks for when a full stack is too much, and covers the long-running runtimes that trade away PHP's shared-nothing simplicity for throughput. The honest summary up front: for most teams either major framework is a fine choice, and the wrong choice is usually no framework at all.

14.1 The Architectural Fork: Active Record vs Data Mapper

The deepest difference between the two frameworks is their persistence pattern, and it is worth choosing on purpose. Active Record (Eloquent) makes the model both the data and its own persistence API: concise, fast to write, and ideal when your objects map closely to tables, which is most CRUD-style applications. Data Mapper (Doctrine) keeps the domain object ignorant of storage and puts persistence in a separate layer: more ceremony, but it keeps a complex domain model clean and storage-independent, which pays off in large applications with rich business rules. If your data model is mostly tables-as-objects, Active Record's brevity wins. If your domain has invariants and behavior that should not be entangled with the database, Data Mapper earns its overhead.

14.2 Laravel vs Symfony in Practice

Decision factors. Neither is "better"; they optimize for different things.
FactorLeans LaravelLeans Symfony
Primary valueSpeed of authorship, convention, developer experienceExplicitness, configurability, long-term maintainability
ORM patternActive Record (Eloquent)Data Mapper (Doctrine)
Team and projectProduct teams, startups, CRUD-heavy apps, fast iterationLarge or regulated orgs, complex domains, multi-team codebases
Upgrade cadenceAnnual major, low-friction by designSix-month minors, predictable two-year LTS
Reuse beyond the appMore monolithicComponents reusable standalone (and used widely elsewhere)
Learning curveGentler startSteeper start, explicit throughout
They are more alike than the debate suggests

Laravel uses Symfony components internally (HttpFoundation, Console, Routing, and others), both auto-escape templates, both parameterize queries, both provide CSRF protection, DI containers, queues, and first-class testing. The Part III defenses are automatic in either. Choose on team fit, domain complexity, and persistence pattern, not on a belief that one is secure and the other is not; both are secure when used as documented.

14.3 Microframeworks and API-First Stacks

When you are building a small service or a focused API and a full framework is more than you need, the microframeworks fit. Slim is a minimal PSR-7/PSR-15 framework: routing and middleware, and you bring the rest. Mezzio (from the Laminas project) is a PSR-15 middleware framework built around explicit composition. Symfony itself scales down well: a minimal install is close to a microframework, and it grows by adding components. For API-heavy work, API Platform (built on Symfony) and Laravel's API tooling generate a lot of the boilerplate. The decision is about scope: a microframework gives you less to learn and less to carry, at the cost of assembling and maintaining the pieces a full framework would have handed you, including the security machinery.

14.4 The Real Cost of No Framework

Writing without any framework is appropriate for a genuinely tiny service or a learning exercise, and rarely otherwise. The reason is security as much as productivity: a framework gives you routing, CSRF protection, auto-escaping templates, parameterized query builders, validation, session hardening, and authentication that have been reviewed by thousands of users. Rebuild all of that yourself and you will reintroduce, somewhere, one of the vulnerabilities Part III spent three chapters eliminating. The vanilla PHP in this guide exists to teach the mechanisms, not to recommend shipping them unframed.

14.5 Long-Running PHP: When Shared-Nothing Goes Away

The shared-nothing model from Section 1.3 assumes the process is recycled between requests. A newer class of runtimes (Swoole, RoadRunner, FrankenPHP, and Laravel Octane on top of them) keeps the PHP application booted in memory and serves many requests per process, eliminating per-request bootstrap and delivering large throughput gains. The trade-off is significant: state now persists between requests within a worker, so a static property or a leaked reference that was harmless under FPM becomes a cross-request data leak or memory leak. You must write for it deliberately.

Caution: long-running runtimes change your correctness model

Under FPM, "forgetting to reset state" is hidden because every request starts clean. Under a long-running runtime it is a bug, and potentially a security bug: data from one user's request can survive into another's. If you adopt Swoole, RoadRunner, FrankenPHP, or Octane, audit for static mutable state, unclosed resources, and globals, and lean on the runtime's documented reset hooks. The performance is real; so is the new class of defects. For most applications, FPM's simplicity is the right default, and you reach for a long-running runtime when measurements justify it.

Exercise 14.1

For each scenario, pick a stack and justify it in one sentence: (a) a two-person startup building a CRUD product under deadline; (b) a bank's internal system with a complex domain model and a five-year horizon; (c) a single stateless webhook receiver; (d) an existing FPM app that has hit a CPU wall on bootstrap overhead. Reference the Active Record vs Data Mapper choice in (a) and (b), and the long-running-runtime trade-off in (d).

Chapter 15Building HTTP APIs

So far the Ledger renders HTML for a person.

The other half of modern PHP work is exposing the same domain as an HTTP API that a program consumes: a mobile app, a single-page front end, another service. The request lifecycle and the Part III defenses are unchanged, but the contract changes. The client is code, not a reader, so the response is structured data, the status code carries meaning the client branches on, errors are machine-readable, and the response shape is a promise you version rather than a page you can restyle at will. This chapter builds a JSON API for the Ledger on the framework from Part IV and the standards that keep it predictable.

15.1 Thinking in Resources

An HTTP API models the domain as resources addressed by URL and acted on with HTTP methods, the style called REST. The Ledger exposes a collection at /invoices and a member at /invoices/{number}, and the method names the operation: GET reads, POST creates, PUT replaces, PATCH updates part of, and DELETE removes. Those verbs are not interchangeable labels; HTTP defines GET as safe (no side effects) and GET, PUT, and DELETE as idempotent (repeating the call lands in the same state), and clients, caches, and proxies rely on those guarantees. Tunneling everything through POST throws that away. JSON is the default representation; set Content-Type: application/json and mean it.

15.2 Status Codes and Content Negotiation

The status code is part of the contract, because a program reads it before it reads the body. Use the codes precisely: 200 for a successful read, 201 with a Location header for a created resource, 204 for a successful call with no body, 400 for a malformed request, 401 for missing or bad authentication, 403 for an authenticated client that is not allowed, 404 for an absent resource, 409 for a conflict, 422 for a well-formed request that fails validation, 429 when rate-limited, and the 5xx range for server faults. The client branches on these, so a wrong code is a broken contract. Honor the client's Accept header (content negotiation); an API that only speaks JSON should say so and return 406 rather than silently sending something else, and it must never fall back to an HTML error page, which an API client cannot parse.

15.3 Errors as Data: Problem Details

An API error must be something a program can parse, not a stack trace and not an HTML page (the leak that Chapter 6 and Chapter 11 warn against, here also a usability failure). The IETF defines a standard JSON error format for exactly this.

Standard · RFC 9457 Problem Details for HTTP APIs

RFC 9457 (July 2023) defines a machine-readable error format carried as the application/problem+json media type: a JSON object with members type (a URI identifying the problem class), title (a short human-readable summary), status (the HTTP status code), detail (specifics for this occurrence), and instance (a URI for this occurrence). It obsoletes the earlier RFC 7807, keeping the same wire format and media type while adding a registry of common problem types and guidance on handling multiple problems (report the single most relevant one; convey multiple occurrences of the same problem type through a problem-specific extension member). Using a single standard error shape means every client parses every error the same way, across every endpoint.IETF RFC 9457, "Problem Details for HTTP APIs" (obsoletes RFC 7807). Maps to OWASP Top 10:2025 A10 (Mishandling of Exceptional Conditions): the detail field carries what the client needs, never an internal stack trace or query.

// a 422 validation failure as application/problem+json
{
    "type":   "https://ledger.example.com/problems/validation",
    "title":  "Your request parameters did not validate.",
    "status": 422,
    "detail": "The field 'number' is required and must be at most 16 characters.",
    "instance": "/invoices"
}

15.4 Versioning and Evolution

An API's shape is a promise to clients you do not control and cannot redeploy, so plan from the start to evolve it without breaking them. Adding a new optional field is a compatible change and needs no ceremony; removing or renaming a field, or changing its type or meaning, is breaking and needs a new version. The two common versioning strategies are URI versioning (/v1/invoices), which is visible, easy to route, and cache-friendly, and media-type versioning (Accept: application/vnd.ledger.v1+json), which keeps URLs clean at the cost of being harder to test and cache. Either works; pick one and apply it consistently rather than mixing them. The discipline that matters more than the choice is treating a breaking change as a deliberate, versioned event, not an accident discovered by a client in production.

15.5 Describing the Contract with OpenAPI

Because the contract is consumed by code, it pays to write it down in a form code can read. OpenAPI is the standard machine-readable description of an HTTP API: its paths, the shape of each request and response, the status codes, and the authentication. From one OpenAPI document you get generated reference docs, client SDKs, request and response validation, and contract tests, which is why the description is treated as part of the contract rather than an afterthought.

Standard · OpenAPI Specification

The OpenAPI Specification is the widely adopted standard for describing HTTP APIs. Version 3.1 aligned the schema language fully with JSON Schema 2020-12, and version 3.2 (September 2025) is the current release, adding first-class support for streaming media types and richer tagging while keeping 3.1 documents working. In PHP you can author it by hand, generate it from PHP attributes on your controllers (for example with the swagger-php attributes), or have a framework derive it from your models, as API Platform does on Symfony; Laravel provides API resources and token authentication (Sanctum) for the same job.OpenAPI Initiative, OpenAPI Specification 3.1 and 3.2 (spec.openapis.org). API token authentication, not session cookies, is the norm for APIs; see the stateless token routes noted in Section 12.3 and the authentication primitives in Chapter 10.

Lab 8 · Expose the Ledger as a JSON API

Goal: give the Ledger a small, standards-correct JSON API on the Part IV framework, with the right status codes, machine-readable errors, and a description.

  1. Add GET /invoices/{number} returning 200 with a JSON invoice, or 404 with an application/problem+json body when it does not exist.
  2. Add POST /invoices that validates input and returns 201 with a Location header on success, or 422 with a problem-details body listing the validation failures.
  3. Protect the write route with API token authentication (the framework's token guard), and confirm a missing token returns 401 and a token without permission returns 403.
  4. Write (or generate) an OpenAPI description of the two endpoints and render it as docs.
  5. Exercise it with curl -i and confirm the status codes, the Content-Type, and the problem+json error shape are exactly as specified.
Exercise 15.1

Explain why returning 200 OK with a body like {"error":"not found"} is worse than returning 404, in terms of what a generic HTTP client, a cache, and a monitoring system each do with the status line. For a request that is well-formed but fails validation, name the correct status code and media type. Finally, explain why adding a new optional field to the invoice response is safe but renaming an existing field is a breaking change.

Part V Testing & Quality

This part is where the code earns trust. Everything to here has taught you to write modern PHP, secure it, and build real applications on Laravel and Symfony; this part proves the result behaves and keeps proving it as the code changes. Chapter 16 teaches unit testing in depth with both PHPUnit and Pest: test doubles, data providers, fixtures, designing for testability, and what code coverage does and does not tell you. Chapter 17 measures test quality with mutation testing using Infection, then tests the Laravel and Symfony applications from Part IV the way each framework intends. Chapter 18 adds static analysis with PHPStan and Psalm, including the security-focused taint analysis, and assembles style, analysis, tests, and a mutation threshold into the single quality gate that Chapter 26 later runs on every deploy. Every example is the Grimoire Ledger.

Chapter 16Testing in Depth

Chapter 6 introduced testing as the regression-detection loop: a test pins a behavior, and the build fails the moment that behavior changes.

That was enough to get a green suite started. This chapter makes you fluent. It covers the two test runners the PHP world actually uses and how they share an engine, the assertions and data providers that keep tests small and precise, the test doubles that isolate a unit from its collaborators, the fixtures and lifecycle hooks that manage state, how to test the database layer honestly, and finally what code coverage measures and (more importantly) what it cannot. The subject under test throughout is the Grimoire Ledger: its Money value object, its Invoice, and the repository that persists them. To keep the focus on testing technique, the examples in this part use a trimmed Invoice (an identifier, a single Money total, and its InvoiceStatus) rather than the full number/lines/status model from Part II; the domain class itself is unchanged.

16.1 What a Unit Test Proves, and What It Does Not

A unit test exercises one unit of behavior in isolation and asserts something concrete about the result. The unit is usually a method or a small cluster of methods on one class, observed only through its public surface. Three properties make a test a unit test rather than something slower and less reliable: it is deterministic (the same inputs always produce the same pass or fail, with no dependence on the clock, the network, random numbers, or the order tests run in), it is isolated (it touches no database, no filesystem, no HTTP, so a failure points at the code and not at the environment), and it is fast (a few milliseconds, so you can run thousands on every save). When a test crosses one of those boundaries (a real database, a real HTTP call) it becomes an integration test: still valuable, covered in Section 16.7, but slower and more fragile, so you write fewer of them.

The shape this implies is the testing pyramid: a broad base of fast unit tests, a smaller band of integration tests that prove the units wire together and talk to real I/O correctly, and a thin cap of end-to-end tests that drive the whole application. The pyramid is a budget, not a law, but inverting it (a handful of slow end-to-end tests and almost no unit tests) is the single most common way a test suite becomes so slow and flaky that the team stops trusting it. Most of your behavior should be pinned by tests at the bottom, where feedback is instant and a failure is unambiguous.

Every good test, at any level, has the same three-part shape, worth making explicit because it keeps tests readable: Arrange the inputs and the object under test, Act by calling the one behavior being tested, and Assert the outcome. One behavior per test, named for what it proves. A test that arranges three times and asserts five unrelated things is really five tests wearing a trench coat, and when it fails you will not know which behavior broke.

Best practice: one reason to fail per test

Name each test after the behavior it pins (it_rejects_a_currency_mismatch, not testMoney2) and assert one logical outcome. When that test goes red, the name alone tells you what regressed. A test with many unrelated assertions forces you to read the body and guess, and it hides later assertions behind the first failure.

16.2 PHPUnit and Pest: Two Front Ends, One Engine

PHPUnit is the long-standing standard test framework for PHP; Pest is a newer runner with a more concise, closure-based syntax. The important fact for choosing is that they are not rivals at the engine level: Pest is built on top of PHPUnit and executes through it, so the two share the same test lifecycle, the same coverage machinery, and the same underlying assertions. A team picks one front end for ergonomics, not for capability. This chapter shows both for every concept so you can read either style in the wild and choose deliberately; the Ledger ships a composer test script that runs whichever the project adopts.

$ composer require --dev phpunit/phpunit  # the engine and its CLI
$ composer require --dev pestphp/pest  # optional: the Pest front end, atop PHPUnit

A PHPUnit test is a method on a class that extends TestCase. Modern PHPUnit attaches metadata with PHP 8 attributes rather than doc-comment annotations; the same MoneyTest from Section 6.3, written the way PHPUnit expects today, declares what it covers and marks its test methods with attributes:

// tests/Unit/Billing/MoneyTest.php
<?php
declare(strict_types=1);

namespace Tests\Unit\Billing;

use App\Billing\Money;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

#[CoversClass(Money::class)]
final class MoneyTest extends TestCase
{
    #[Test]
    public function it_adds_amounts_of_the_same_currency(): void
    {
        $sum = (new Money(1299))->add(new Money(1));
        $this->assertSame(1300, $sum->cents);
    }

    #[Test]
    public function it_rejects_a_currency_mismatch(): void
    {
        $this->expectException(\DomainException::class);
        (new Money(100, 'USD'))->add(new Money(100, 'EUR'));
    }
}
Standard · Test metadata is attributes, not annotations

Support for metadata in doc-comment annotations (@test, @dataProvider, @covers) was deprecated in PHPUnit 11 and removed in PHPUnit 12; use the equivalent attributes (#[Test], #[DataProvider], #[CoversClass]) instead. PHPUnit reads attributes in preference to comments, so a project mid-migration can carry both, but new code should be attribute-only.PHPUnit Manual, "Attributes" (PHPUnit 12.5); Release Announcement for PHPUnit 12. Current stable line is PHPUnit 13.

The runner is configured by a phpunit.xml at the project root: it bootstraps Composer's autoloader, names the test directory, and declares which source the coverage report should measure. Keeping the <source> element pointed at src/ is what later lets a coverage run say something meaningful (Section 16.8).

// phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         bootstrap="vendor/autoload.php"
         colors="true"
         failOnRisky="true"
         failOnWarning="true">
    <testsuites>
        <testsuite name="default">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <source>
        <include><directory>src</directory></include>
    </source>
</phpunit>

The same two behaviors in Pest are closures registered with it() (or test()), and assertions read as expect(...)->toBe(...). There is no class and no boilerplate; Pest discovers any *Test.php file under tests/ and the expect() API is just a fluent wrapper over PHPUnit's assertions:

// tests/Unit/Billing/MoneyTest.php  (Pest)
<?php
declare(strict_types=1);

use App\Billing\Money;

it('adds amounts of the same currency', function (): void {
    expect((new Money(1299))->add(new Money(1))->cents)->toBe(1300);
});

it('rejects a currency mismatch', function (): void {
    expect(fn () => (new Money(100, 'USD'))->add(new Money(100, 'EUR')))
        ->toThrow(DomainException::class);
});
Note: Pest's distinctive features

Because Pest 4 runs on PHPUnit 12, anything PHPUnit can do, Pest can do. Pest layers on conveniences worth knowing: datasets (Section 16.4), an expect() API with higher-order chaining, a built-in architecture-testing API (arch()), a fast type-coverage engine, and first-class browser testing. None of that changes the engine; it changes how the tests read.

16.3 Assertions and Expectations

The assertion is where a test earns its keep, and the most consequential choice is identity versus equality. assertSame($a, $b) requires ===: same type and, for objects, the same instance. assertEquals requires only ==, which coerces types and compares objects field by field. For a typed value object like Money, you almost always want assertSame on its scalar properties, because the entire point of the type is that 1300 the integer and "1300" the string are different values. A test that uses assertEquals(1300, $sum->cents) would pass even if add() started returning a numeric string, silently undoing the type guarantee the value object exists to provide.

// identity vs loose equality: the difference that matters for value objects
$this->assertSame(1300, $sum->cents);  // 1300 === 1300 (int), strict
$this->assertEquals(1300, $sum->cents);  // 1300 == "1300" would also pass: avoid for scalars

// asserting an exception is part of the contract, not an error in the test
$this->expectException(\DomainException::class);
$this->expectExceptionMessage('currency');
(new Money(100, 'USD'))->add(new Money(100, 'EUR'));

Pest draws the same line with two expectations: ->toBe() is strict (===) and ->toEqual() is loose (==); exceptions are asserted by wrapping the offending call in a closure and using ->toThrow(). Pest expectations also chain, which lets one statement make several related claims about a value without three separate assertions:

expect($invoice)
    ->total->cents->toBe(1300)
    ->total->currency->toBe('USD')
    ->and($invoice->status)->toBe(InvoiceStatus::Paid);

Whichever front end you use, assert the behavior, not the implementation. Asserting that a method returns the right total is durable; asserting that it called three private helpers in a particular order pins the current code in place and turns every refactor into a test rewrite. Good assertions describe what the unit promises its callers.

16.4 Data Providers and Parameterized Tests

When several tests differ only in their inputs and expected outputs, copying the test body once per case is noise that hides the pattern and rots quickly. A data provider turns that into one test run many times. In PHPUnit, a provider is a static method returning an iterable of argument tuples, attached with #[DataProvider]; naming the cases (the array keys) makes a failure report say which case broke:

use PHPUnit\Framework\Attributes\DataProvider;

#[Test]
#[DataProvider('additionCases')]
public function it_adds_correctly(int $a, int $b, int $expected): void
{
    $this->assertSame($expected, (new Money($a))->add(new Money($b))->cents);
}

public static function additionCases(): array
{
    return [
        'two positives'      => [1299, 1, 1300],
        'adding zero'        => [500, 0, 500],
        'large values'       => [2_000_000, 999, 2_000_999],
    ];
}

Pest expresses the same idea with ->with() datasets, which can be inline, named, or shared across files in a datasets/ directory:

it('adds correctly', function (int $a, int $b, int $expected): void {
    expect((new Money($a))->add(new Money($b))->cents)->toBe($expected);
})->with([
    'two positives' => [1299, 1, 1300],
    'adding zero'   => [500, 0, 500],
    'large values'  => [2_000_000, 999, 2_000_999],
]);

The value is not just brevity. A provider invites you to enumerate the boundaries (zero, the maximum, the off-by-one either side of a limit) in one place, so the edge cases that actually break code become a visible, growable list rather than an afterthought. When a bug is found, the fix is to add the failing input as a named case, which both reproduces the bug and prevents its return.

16.5 Test Doubles, and Designing for Them

A unit under test usually depends on collaborators: InvoiceService needs a repository to save through, a clock to date an invoice, a mailer to send a receipt. To test the service in isolation you replace those collaborators with stand-ins called test doubles. The canonical taxonomy, from Gerard Meszaros, names five by their job. A dummy is passed only to fill a parameter and is never used. A stub returns canned answers so the unit has something to work with. A spy is a stub that also records how it was called, for assertion afterward. A mock is configured up front with the exact calls it expects and fails the test if they do not happen. A fake is a real, working but simplified implementation, the classic example being an in-memory repository that satisfies the interface without a database.

None of this is possible unless the unit accepts its collaborators from outside, which is why dependency injection (Chapter 4) and testing are the same discipline viewed from two angles. The injection point is the seam: the place you can substitute a double. A class that news up its own PDO connection in its constructor has no seam and cannot be unit-tested; the same class taking an InvoiceRepository interface as a constructor argument can be handed a fake in a test and the real thing in production.

// A stub: canned return value, no expectations about how it is called.
$clock = $this->createStub(Clock::class);
$clock->method('now')->willReturn(new \DateTimeImmutable('2026-01-01T00:00:00Z'));

// A mock: the test fails unless send() is called exactly once with a Receipt.
$mailer = $this->createMock(Mailer::class);
$mailer->expects($this->once())
       ->method('send')
       ->with($this->isInstanceOf(Receipt::class));

$service = new InvoiceService($repository, $clock, $mailer);
$service->markPaidAndNotify($draft);  // mock verifies on tearDown

For a repository, a fake is usually better than a mock. An in-memory implementation of the interface is a few lines, reads naturally, and lets the test assert on real outcomes (the invoice can be read back) rather than on the fact that save() was called:

final class InMemoryInvoiceRepository implements InvoiceRepository
{
    /** @var array<string, Invoice> */
    private array $store = [];

    public function save(Invoice $invoice): void { $this->store[$invoice->id] = $invoice; }
    public function find(string $id): ?Invoice  { return $this->store[$id] ?? null; }
}

#[Test]
public function it_persists_a_paid_invoice(): void
{
    $repo    = new InMemoryInvoiceRepository();
    $service = new InvoiceService($repo, $this->fixedClock(), $this->nullMailer());

    $invoice = $service->markPaid($this->draftInvoice());

    $this->assertSame($invoice, $repo->find($invoice->id));  // assert the outcome, not the call
}

Pest can use PHPUnit's doubles directly, and also integrates the Mockery library (mock(Mailer::class)->shouldReceive('send')->once()) for those who prefer its expectation syntax. The choice of library matters far less than the choice of how much to double.

Caution: over-mocking tests the mock, not the code

Every mock encodes an assumption about how the unit collaborates, so a suite that mocks everything passes as long as the code keeps calling the mocks the way the test expects, even when the real behavior is wrong. Mock at architectural boundaries you genuinely want to keep out of a unit test (the database, the network, the system clock, the mailer); use real objects or simple fakes for everything cheap and deterministic, including value objects like Money. A test that mocks Money is testing nothing.

16.6 Fixtures and the Test Lifecycle

A fixture is the known state a test runs against: the objects, the data, the configuration arranged before the act. PHPUnit gives every test method a fresh instance of the test class and runs lifecycle hooks around it: setUp() before each test, tearDown() after, and the attribute-based #[Before] and #[After] for additional hooks. Pest spells the same hooks beforeEach() and afterEach(). Use them to build the common arrangement once, but keep them small; a giant setUp() that prepares state most tests ignore makes every test slower and harder to read.

final class InvoiceServiceTest extends TestCase
{
    private InMemoryInvoiceRepository $repo;
    private InvoiceService $service;

    protected function setUp(): void
    {
        $this->repo    = new InMemoryInvoiceRepository();
        $this->service = new InvoiceService($this->repo, $this->fixedClock(), $this->nullMailer());
    }

    private function draftInvoice(): Invoice { /* a valid draft, built one way, in one place */ }
}

The non-negotiable property is isolation: each test must start from the same clean state and leave nothing behind that another test could see. Tests that share mutable state (a static property, a row left in a table, a file on disk) become order-dependent and flaky, passing alone and failing in the suite or vice versa, which is corrosive because the failure has nothing to do with the code under test. When you need many similar objects, a small factory (sometimes called an Object Mother) that returns a valid Invoice with sensible defaults and lets each test override the one field it cares about keeps the arrangement honest and the intent visible.

16.7 Testing the Database Layer Honestly

Unit tests stop at the boundary, but the boundary itself needs testing, and that is where new developers most often go wrong by mocking the database. A mock of PDO proves only that your code calls the methods you told the mock to expect; it cannot catch a malformed INSERT, a column-type mismatch, a broken transaction, or a query that is valid SQL but returns the wrong rows. Those bugs live precisely in the interaction with the real engine, so the repository must be tested against a real database. That makes it an integration test, and the techniques that keep integration tests fast and isolated are worth getting right.

The core technique is per-test transactional rollback: open a transaction in setUp() and roll it back in tearDown(), so every test sees a clean database and nothing it writes survives. Combined with a schema created once, this gives integration tests that are isolated and nearly as fast as the writes themselves:

final class PdoInvoiceRepositoryTest extends TestCase
{
    private \PDO $pdo;

    protected function setUp(): void
    {
        $this->pdo = new \PDO('sqlite::memory:');
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->pdo->exec(
            'CREATE TABLE invoices (id TEXT PRIMARY KEY, cents INTEGER NOT NULL, currency TEXT NOT NULL)'
        );
    }

    #[Test]
    public function it_round_trips_an_invoice(): void
    {
        $repo = new PdoInvoiceRepository($this->pdo);
        $repo->save(new Invoice('inv-1', new Money(1300, 'USD')));

        $found = $repo->find('inv-1');
        $this->assertSame(1300, $found->total->cents);
        $this->assertSame('USD', $found->total->currency);
    }
}
Caution: an in-memory database is fast but not faithful

SQLite in memory makes the suite quick and needs no service running, which is ideal when your SQL is portable. But it is not the engine you run in production, and it will silently accept or reject things differently (data types, JSON functions, window functions, strictness, locking). Where a repository depends on engine-specific SQL, test it against the same engine you deploy (MariaDB or PostgreSQL) in CI, using the transaction-rollback pattern for isolation. This is a real conflict between speed and fidelity: choose per repository, and when in doubt, favor fidelity for code whose bugs would reach production data. The Laravel and Symfony chapters (Chapter 12, Chapter 13) build on this with framework tooling that wraps each test in a transaction for you.

16.8 Code Coverage and Its Limits

Code coverage measures which lines (and, with the right driver, which branches) of your source were executed while the suite ran. It is collected by an external driver, and the choice of driver is a real engineering decision. Xdebug is mature and supports line, branch, and path coverage, but it is slow and memory-hungry. PCOV is a purpose-built coverage driver that supports line coverage only, but is dramatically faster and allocates almost nothing, which makes it the right choice for the coverage run in CI unless you specifically need branch coverage. Both collect at the bytecode level and both are read by PHPUnit's coverage subsystem; you switch between them by which extension is loaded.

$ XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-text  # Xdebug: line + branch + path
$ php -d pcov.enabled=1 vendor/bin/phpunit --coverage-text  # PCOV: line only, much faster
  Summary:
    Lines:   94.2% (1308/1389)
    Methods: 96.0% (240/250)
Standard · Coverage drivers and what they measure

PHPUnit can collect coverage with either Xdebug or PCOV. To report branch and path coverage, data must be collected with Xdebug; PCOV supports line coverage only and is substantially faster. Line coverage records that a line ran; branch coverage records that each side of every conditional ran, which is strictly stronger.PHPUnit Manual, "Code Coverage" (PHPUnit 12.5); Xdebug Documentation, "Code Coverage Analysis"; PCOV (krakjoe/pcov) README.

The danger is treating the percentage as a quality score. Coverage is a measure of execution, not of verification: a line is "covered" the instant a test runs it, whether or not any assertion checks what it did. It is trivial to reach high line coverage with tests that assert nothing meaningful, and a test suite can report 100% coverage while failing to catch obvious bugs. Coverage answers one question well (which code has no test exercising it at all, a genuine blind spot worth fixing) and a different question not at all (whether the tests that do run would notice if the code were wrong). That second question is what mutation testing answers, and it is the subject of Chapter 17.

Best practice: a coverage floor, not a coverage target

Set a minimum line-coverage threshold in CI (commonly somewhere in the 80s for application code) to catch whole files or methods that nobody tested, and let it block a merge. But do not chase 100%, and never let coverage stand in for test quality. Goodhart's law applies: once coverage becomes the target, it stops measuring anything, because the cheapest way to raise it is to add assertion-free tests. Use it as a smoke detector for untested code, then use mutation testing to judge whether the tests you have are any good.

Lab 9 · Build a real unit suite for the Ledger

Goal: write a fast, isolated unit suite for the Ledger's domain and service layer using both runners, a data provider, a fake repository, and a coverage run, and see coverage's blind spot first-hand.

  1. Install the runners: composer require --dev phpunit/phpunit pestphp/pest. Add the phpunit.xml from Section 16.2 with <source> pointed at src/, and a composer test script.
  2. Write MoneyTest in PHPUnit using attributes (#[CoversClass], #[Test], #[DataProvider]): cover addition, the currency-mismatch exception, and a provider of at least five boundary amounts. Then mirror two of those tests in Pest with it() and ->with(), and confirm composer test runs both.
  3. Write InvoiceServiceTest that injects an InMemoryInvoiceRepository fake and a stubbed Clock, marks a draft paid, and asserts the invoice can be read back from the fake. Use a setUp() fixture and a private draftInvoice() factory.
  4. Add a PdoInvoiceRepositoryTest against sqlite::memory: that round-trips an invoice. Note in a comment which assertion would not hold against your production engine, if any.
  5. Install PCOV and run php -d pcov.enabled=1 vendor/bin/phpunit --coverage-text. Now deliberately weaken one test (delete its assertion body but keep the call) and re-run: watch coverage stay high while the test proves nothing. This is the gap Chapter 17 closes.
Exercise 16.1

A teammate reports 100% line coverage on Money and argues it is fully tested. Explain why that number alone does not prove add() is correct. Then describe one change to add() (for example, returning $this unchanged, or swapping a + for a -) that the three original tests from Section 6.3 might still report as fully covered yet failing to catch, and name the kind of tool that is designed to find exactly that weakness.

Chapter 17Mutation & Framework Testing

Section 16.8 ended on a hard limit: coverage tells you which code ran, never whether your tests would notice if that code were wrong.

This chapter closes that gap with mutation testing, which deliberately breaks your code and checks whether a test complains, and gives you a real measure of test strength. It then turns the deep testing skills from Chapter 16 on the frameworks themselves: testing a Laravel application and a Symfony application the way each is designed to be tested, with their database, HTTP, and service-container tooling. The Ledger remains the worked example, now as a framework application rather than a handful of plain classes.

17.1 What Mutation Testing Measures

Mutation testing inverts the usual question. Instead of asking whether your tests pass, it asks whether they would fail when they should. The tool makes many small, deliberate edits to your source, one at a time (a + becomes a -, a < becomes a <=, a return true becomes return false, a method call is removed), and after each edit it runs the tests. Each edited version is a mutant. If at least one test fails, the mutant is killed: your suite noticed the fault. If every test still passes, the mutant escaped: you changed the behavior of the program and not one test cared. Each escaped mutant is a concrete, located hole in your tests, far more actionable than a coverage percentage.

The headline metric is the Mutation Score Indicator (MSI): the share of mutants your suite detected. Because some mutants land on lines no test executes at all, a second metric, Covered Code MSI, computes the same ratio over only the mutants on covered lines, which separates the strength of your tests from their reach. A project with 95% line coverage and 60% MSI is telling you something precise and uncomfortable: the tests run almost all the code but verify little of it. That is exactly the situation Section 16.8 warned coverage cannot detect.

Standard · The Mutation Score Indicator

Infection's MSI is the percentage of generated mutants that were detected, where a mutant counts as detected if a test failed (killed it), the code errored, or the run timed out. Covered Code MSI is the same ratio restricted to mutants on code the test suite actually executes. Both are exposed as CI thresholds (minMsi and minCoveredMsi in the configuration, or --min-msi and --min-covered-msi on the command line), which fail the build when test strength drops below the floor.Infection documentation, "Mutation Score Indicator (MSI)" and "Using with CI" (infection.github.io).

17.2 Infection in Practice

Infection is the mutation-testing framework for PHP. Install it as a dev dependency and describe, in infection.json5, which source it should mutate, which mutators to apply (the @default profile is the right starting point), and where to write its logs:

$ composer require --dev infection/infection
// infection.json5
{
    "$schema": "vendor/infection/infection/resources/schema.json",
    "source": { "directories": ["src"] },
    "mutators": { "@default": true },
    "logs": { "text": "build/infection.log", "html": "build/infection.html" },
    "minMsi": 80,
    "minCoveredMsi": 90
}

Infection works by first collecting coverage (it drives PHPUnit or Pest for you, so it needs Xdebug or PCOV loaded), then generating mutants and, crucially, running only the tests that cover each mutated line. That is what makes it tractable: a naive implementation would run the whole suite once per mutant, but Infection runs only the relevant tests and parallelizes across cores with --threads. A run prints a per-category tally and the metrics:

$ vendor/bin/infection --threads=max --min-msi=80 --min-covered-msi=90
13 mutations were generated:
      11 mutants were killed
       1 mutant was not covered by tests
       1 covered mutant was not detected

Metrics:
    Mutation Score Indicator (MSI): 84.62%
    Mutation Code Coverage:         92.31%
    Covered Code MSI:               91.67%

The one covered mutant that was not detected is the interesting line. Suppose Money's constructor guards against negative amounts with if ($cents < 0), and the only test for it asserts that new Money(-1) throws. Infection applies its conditional-boundary mutator and the test suite stays green:

// Escaped mutant (Infection's ConditionalBoundary): the suite did not notice.
- if ($cents < 0) {
+ if ($cents <= 0) {
      throw new \InvalidArgumentException('Money cannot be negative.');
  }

The mutant survives because no test ever constructs new Money(0) and asserts it is allowed. The mutation flips the boundary so zero is now rejected, and since nothing exercises zero, nothing fails. That is a genuine gap: the contract says zero is a valid amount, and you never pinned it. The fix is one test, and it both kills the mutant and documents the boundary.

#[Test]
public function it_allows_a_zero_amount(): void
{
    $this->assertSame(0, (new Money(0))->cents);  // kills the < -> <= mutant
}

17.3 Acting on Escaped Mutants, and Where to Run Infection

The workflow that makes mutation testing pay is to treat each escaped mutant as a precise to-do: read the diff, decide whether the changed behavior should be caught (it almost always should), and write the one test that would have killed it. Worked through a domain model, this converges fast, because most escaped mutants cluster on boundaries and guard clauses you forgot to pin, and each fix is small. The result is a suite you can actually trust to catch regressions, which is the entire point of testing.

Two practical cautions keep mutation testing from becoming a chore. First, a small number of mutants are equivalent: the mutation produces a program that behaves identically, so no test can kill it and chasing it is wasted effort (a classic case is mutating a value used only in a log message). Infection lets you ignore specific mutators or lines so equivalent mutants do not hold the score hostage. Second, a full mutation run is heavier than a unit run, so the common pattern is to run Infection only over the code changed in a branch (--git-diff-filter=AM compares against the base branch) on every pull request, and run the full suite on a schedule. On an existing codebase with weak tests, set minCoveredMsi to today's number and ratchet it upward, exactly as you would a static-analysis baseline (Chapter 18); never let it fall.

Best practice: mutate the domain, not the framework

Mutation testing earns the most on pure, logic-dense code: value objects, domain services, calculators, state machines. It earns the least on thin framework glue (controllers, configuration, wiring) where there is little behavior to mutate and the tests are slow integration tests. Point Infection's source.directories at your domain layer and let the framework feature tests (the rest of this chapter) cover the glue. You get a meaningful MSI on the code where correctness matters, without paying to mutate code that is mostly declaration.

17.4 Testing a Laravel Application

Laravel's testing story is built into the framework, and a new application scaffolds a working test suite on the first composer create-project. Tests split into two kinds by what they boot. A unit test extends PHPUnit's plain TestCase and tests a class in isolation, exactly as Chapter 16 describes. A feature test extends the application's Tests\TestCase, which boots the full framework (the container, routing, middleware), so it can drive the app through HTTP and the database. Both PHPUnit and Pest are first-class; recent Laravel scaffolds default the runner to Pest, and the examples below show each.

The database tooling is the part worth learning first, because it solves the isolation problem from Section 16.7 for you. The RefreshDatabase trait migrates a test database once and wraps every test in a transaction that is rolled back at the end, so each test sees a clean schema and leaves nothing behind. Model factories generate valid records without hand-writing inserts, and assertDatabaseHas checks persisted state:

// tests/Feature/InvoiceApiTest.php  (PHPUnit style)
<?php
declare(strict_types=1);

namespace Tests\Feature;

use App\Models\Invoice;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

final class InvoiceApiTest extends TestCase
{
    use RefreshDatabase;

    #[Test]
    public function it_creates_an_invoice_over_http(): void
    {
        $response = $this->postJson('/api/invoices', [
            'cents' => 1300, 'currency' => 'USD',
        ]);

        $response->assertCreated()->assertJsonPath('data.cents', 1300);
        $this->assertDatabaseHas('invoices', ['cents' => 1300, 'currency' => 'USD']);
    }

    #[Test]
    public function it_rejects_an_unknown_currency(): void
    {
        Invoice::factory()->create(['currency' => 'USD']);
        $this->postJson('/api/invoices', ['cents' => 1300, 'currency' => 'ZZZ'])
             ->assertStatus(422);
    }
}

The same test in Pest drops the class and applies the trait with uses(), which is typically declared once in tests/Pest.php for an entire directory:

// tests/Feature/InvoiceApiTest.php  (Pest style)
<?php
use App\Models\Invoice;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('creates an invoice over HTTP', function (): void {
    $this->postJson('/api/invoices', ['cents' => 1300, 'currency' => 'USD'])
        ->assertCreated()
        ->assertJsonPath('data.cents', 1300);

    $this->assertDatabaseHas('invoices', ['cents' => 1300]);
});

The other half of Laravel's test kit is its fakes, which swap a whole subsystem for an in-memory recorder so a feature test stays fast and deterministic without touching the outside world. Mail::fake() then Mail::assertSent(ReceiptMail::class) proves an email would have gone out without sending one; Queue::fake() and Queue::assertPushed() prove a job was dispatched without running a worker; Http::fake() stubs outbound HTTP; Storage::fake('s3') gives a real filesystem API over a temporary disk; and time is controllable with $this->travelTo(). These are the framework's built-in test doubles, and they are the right tool at the feature level where constructing PHPUnit mocks for framework services would be painful and brittle. Chapter 12 covers how these services are wired; here the point is that every one of them has a test-time fake.

Note: keep the testing pyramid even inside a framework

Feature tests that boot the framework and hit the database are integration tests: invaluable, but an order of magnitude slower than the unit tests of Chapter 16. Test the Ledger's pricing and currency rules as plain unit tests on the domain classes, and reserve feature tests for the things only a booted app exercises: routing, validation, authorization, serialization, and persistence. A suite that is all feature tests is the inverted pyramid in framework clothing.

17.5 Testing a Symfony Application

Symfony provides the same capabilities through a slightly different door, and installing symfony/test-pack pulls in PHPUnit, the assertions, and the browser tooling in one step. Two base classes anchor everything. KernelTestCase boots the kernel and exposes the service container through static::getContainer(), which is how you integration-test a service with its real dependencies wired by the framework. WebTestCase extends it and adds static::createClient(), a browser that sends requests through the full HTTP stack without a running web server, for functional tests of endpoints.

// tests/Functional/InvoiceApiTest.php
<?php
declare(strict_types=1);

namespace App\Tests\Functional;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

final class InvoiceApiTest extends WebTestCase
{
    public function testItCreatesAnInvoiceOverHttp(): void
    {
        $client = static::createClient();
        $client->request('POST', '/api/invoices', server: [
            'CONTENT_TYPE' => 'application/json',
        ], content: json_encode(['cents' => 1300, 'currency' => 'USD']));

        self::assertResponseStatusCodeSame(201);
        $data = json_decode($client->getResponse()->getContent(), true, flags: JSON_THROW_ON_ERROR);
        self::assertSame(1300, $data['cents']);
        self::assertSame('USD', $data['currency']);
    }
}

Symfony's built-in assertions cover the response, its headers and cookies, and the matched route; there is no built-in JSON assertion, so decode the body and assert on the data as above. (API Platform's ApiTestCase adds assertJsonContains() and JSON-schema assertions for teams on that stack.)

To integration-test a service rather than an endpoint, boot the kernel and pull the real object out of the container, letting Symfony's dependency injection assemble it exactly as in production:

$container = static::getContainer();
$service   = $container->get(InvoiceService::class);
$invoice   = $service->markPaid($draft);
self::assertSame(InvoiceStatus::Paid, $invoice->getStatus());

For the database, Doctrine is the standard, and the cleanest isolation comes from the dama/doctrine-test-bundle, which wraps every test in a transaction and rolls it back automatically, the framework-level equivalent of the pattern in Section 16.7. Test data is built with fixtures or, more ergonomically, a factory library such as Foundry. One more piece is specific to Symfony and worth enabling: the PHPUnit Bridge tracks deprecation notices triggered during the suite and can fail the build when your code (or a dependency) uses something slated for removal, which turns the test run into an early-warning system for the upgrades covered in Chapter 27.

Standard · Framework testing follows the framework's own guidance

Laravel and Symfony each document a testing approach that integrates with their container, database layer, and HTTP kernel; their documentation is the authoritative source for that framework, since no external standard governs it. Laravel's tooling centers on the RefreshDatabase trait, model factories, HTTP test assertions, and the facade fakes; Symfony's centers on KernelTestCase and WebTestCase, the test container, the PHPUnit Bridge, and the recommended transactional test bundle.Laravel Documentation, "Testing: Getting Started", "HTTP Tests", and "Database Testing" (Laravel 13). Symfony Documentation, "Testing" (Symfony 8.x).

Lab 10 · Measure test strength, then test the framework

Goal: raise the Ledger's domain MSI with Infection by killing a real escaped mutant, then write a framework feature test that exercises the invoice endpoint end to end.

  1. Install Infection (composer require --dev infection/infection) and add the infection.json5 from Section 17.2, pointing source.directories at the domain code only. Run vendor/bin/infection --threads=max and record the MSI and Covered Code MSI.
  2. Find one covered-but-undetected mutant in the run's HTML log. Read the diff, confirm the behavior change should be caught, and write the single test that kills it (the new Money(0) boundary test in Section 17.2 is the likely one). Re-run and watch the MSI rise.
  3. Set minCoveredMsi to the number you just reached and add infection to the composer check script so the threshold gates the build, mirroring the static-analysis baseline of Chapter 18.
  4. For your framework of choice, write one feature test of POST /api/invoices. In Laravel, use RefreshDatabase, a factory, postJson, and assertDatabaseHas. In Symfony, use WebTestCase, dama/doctrine-test-bundle, and assertResponseStatusCodeSame. Assert both the HTTP response and the persisted row.
  5. Add one fake-backed assertion: prove a receipt email would be sent on success without sending it (Mail::fake() in Laravel, or assert on a mailer collector in Symfony).
Exercise 17.1

A service reports 92% line coverage but 58% MSI. In your own words, what does each number say about the test suite, and which one would you rather improve first and why? Separately, explain what an equivalent mutant is, why it can never be killed, and why a rising count of them is a reason to refine your mutators rather than to write more tests.

Chapter 18Static Analysis & Quality Gates

Tests prove that the code behaves correctly for the inputs you thought to try; static analysis proves properties of the code over every path, without running it at all.

The two catch different bugs, and a serious project runs both. Section 5.4 introduced PHPStan and Psalm as part of the toolchain; this chapter goes deep: the level ladder you climb to make PHP feel statically typed, the docblock generics that let the analyzer reason about collections and repositories, the taint analysis that turns Psalm into a security tool, the extensions that teach the analyzers about Laravel and Symfony, and finally the single quality gate that binds style, analysis, tests, and mutation score into one command that Chapter 26 runs on every deploy.

18.1 What Static Analysis Proves

A static analyzer reads your source and proves things about it by reasoning over the types and control flow: that a method is passed the types it declares, that a nullable value is checked before it is dereferenced, that a called method exists, that every arm of a match is handled, that a branch is not dead, that a returned value matches the declared return type. It does this for every possible execution, not just the inputs a test happens to supply, which is its central advantage and the reason it complements testing rather than competing with it. A test tells you the invoice total is right for the three cases you wrote; the analyzer tells you that total() can never return null on any path, because the types do not permit it. Neither subsumes the other.

The practical effect of running a high analysis level alongside declare(strict_types=1) is that a large class of bugs becomes impossible to commit: the typo'd property, the method renamed in one place but called in another, the null that slips through one branch, the argument passed in the wrong order when the types differ. These are the bugs that, untyped, surface as a fatal error in production at 3 a.m. The analyzer moves them to the second before you push.

Note: there is no formal standard for PHP static analysis

As with the PHP runtime itself (Section 5.4), no DISA STIG, CIS Benchmark, or other external standard governs static analysis of PHP. The analyzers define their own rule levels, and their documentation is the authoritative reference. This chapter treats the PHPStan and Psalm documentation as primary sources, which is what the project preferences and the series editorial rules call for when no higher standard exists.

18.2 PHPStan's Rule Levels, Baselines, and Strictness

PHPStan grades its strictness in eleven levels, 0 (loosest) through 10 (strictest), selected with --level or in the config. Each level switches on more checks: low levels catch undefined variables, unknown methods, and wrong argument counts; the middle levels enforce type compatibility on arguments, returns, and properties; the high levels close the gaps that let untyped values hide, culminating at level 10, which reports even implicit mixed (a value whose type was never declared), so nothing escapes the type system by omission. You can write --level max to always track the current ceiling. The standing advice is to run new code at the highest level the team can sustain (8 and up) and to adopt analysis on an existing codebase at a low level, then ratchet upward one step at a time.

Standard · PHPStan rule levels 0 through 10

PHPStan offers eleven rule levels (0 is the loosest, 10 the strictest), chosen with the -l/--level flag, with max as an alias for the highest. The default is level 0, and the design intent is incremental adoption: start low, raise the level as the build allows. PHPStan 2.0 added level 10, which reports implicit mixed in addition to explicit mixed. For strictness beyond the levels, the first-party phpstan-strict-rules extension adds defensive-programming rules.PHPStan Documentation, "Rule Levels"; PHPStan blog, "PHPStan 2.0 Released With Level 10" (phpstan.org). Current major line is PHPStan 2.

The mechanism that makes adoption realistic on a large legacy codebase is the baseline. Running phpstan analyse --generate-baseline writes every current error into phpstan-baseline.neon, which the config then includes; PHPStan ignores those recorded errors so the build goes green, while still failing on any new error introduced afterward. The baseline is a debt ledger: it freezes the existing problems so they cannot grow, and you pay them down by deleting entries and fixing the code. This is how you raise a legacy project to a high level without a single impossible commit that fixes everything at once.

# phpstan.neon
includes:
    - phpstan-baseline.neon
    - vendor/phpstan/phpstan-strict-rules/rules.neon
parameters:
    level: 9
    paths:
        - src
        - tests

When you must suppress a specific error (a genuine false positive, or a deliberate exception), do it narrowly using the error's identifier rather than a blanket mute. Every PHPStan error carries an identifier such as argument.type or return.type, and an inline @phpstan-ignore comment naming that identifier suppresses exactly that one error and nothing else, so an unrelated bug on the same line is still caught:

// @phpstan-ignore argument.type (third-party stub is wrong; tracked in TICKET-123)
$client->send($payload);

18.3 Generics and Precise Types in Docblocks

PHP's native type system stops at array: the language cannot say "a list of Invoice" or "a collection parameterized by whatever type it was created with". Static analyzers fill that gap by reading a richer type language out of docblocks, which PHP ignores as comments but the analyzer treats as binding contracts. This is where analysis stops being a linter and becomes a genuine type checker. The everyday forms are array shapes and value constraints: array<int, Invoice>, list<Money> (a zero-indexed array), non-empty-string, int<0, max>, and class-string<Invoice> (a string that must name the Invoice class or a subclass).

final class InvoiceService
{
    /**
     * @param  list<Invoice>  $invoices  zero or more invoices to total
     * @return Money                     the sum, in the shared currency
     */
    public function totalOf(array $invoices): Money
    {
        // PHPStan now knows each element is an Invoice, and flags it if a caller
        // passes list<string> or reads a property Invoice does not have.
        return array_reduce(
            $invoices,
            fn (Money $carry, Invoice $i): Money => $carry->add($i->total),
            new Money(0),
        );
    }
}

The full power shows up with generics proper. A reusable collection is declared with @template, and the analyzer then tracks the element type through every use, so reading the wrong type out of a Collection<Invoice> is an analysis error caught before the code runs:

/**
 * @template T
 */
final class TypedCollection
{
    /** @var list<T> */
    private array $items = [];

    /** @param T $item */
    public function add(mixed $item): void { $this->items[] = $item; }

    /** @return list<T> */
    public function all(): array { return $this->items; }
}

// @var TypedCollection<Invoice> $invoices  -- the analyzer carries Invoice through .all()

These annotations are a contract you keep honest with the analyzer's help: if add() is later called with a Money where an Invoice was expected, the build fails. Psalm understands the same vocabulary (with some @psalm-prefixed extensions for its stricter checks), so the investment in precise docblocks pays off whichever analyzer you run, and it makes the code self-documenting in the bargain.

18.4 Psalm and Security Taint Analysis

Psalm is the other major analyzer, comparable to PHPStan in its core job and graded by an errorLevel that runs the opposite direction (1 is strictest, 8 is loosest, which trips up newcomers who expect PHPStan's numbering). Running both analyzers is possible but usually redundant; most teams pick one for general analysis. What can justify keeping Psalm in the toolchain even alongside PHPStan is a capability PHPStan does not match: taint analysis, a static security check.

Taint analysis tracks the flow of untrusted data through the program. Anything a user controls is a taint source; a place where untrusted data is dangerous is a taint sink. Psalm follows every path from source to sink and reports any that arrives without being sanitized, proving the absence of a whole category of injection bug across the entire codebase at once, not just on the inputs a test tried. Run it with a flag:

$ vendor/bin/psalm --taint-analysis
ERROR: TaintedHtml - src/Invoice/InvoiceController.php:42:16
  - $_GET['note'] flows to echo without being escaped (XSS)
    $_GET (taint source) -> $note -> echo (taint sink)
Standard · Psalm taint sources and sinks

Psalm's taint analysis (--taint-analysis) tracks data from taint sources to taint sinks and flags any unsanitized flow. The default sources are the $_GET, $_POST, and $_COOKIE superglobals; the built-in sinks include echo (cross-site scripting), the PDO query methods (SQL injection), include, and header. Custom sources, sinks, and escapers are declared with @psalm-taint-source, @psalm-taint-sink, and @psalm-taint-escape. This is a static, whole-program complement to the runtime defenses of Chapter 9.Psalm Documentation, "Security Analysis" (psalm.dev/docs/security_analysis).

This connects static analysis directly to the threat model of Chapter 8. A unit test for the invoice endpoint checks that it returns the right data; it will not notice that a note field is echoed without encoding, because the test sends benign input. Taint analysis notices, because it reasons about what could flow there from a source. It belongs in CI for any application that handles untrusted input, which is all of them.

18.5 Teaching the Analyzer About Your Framework

Run PHPStan at level 9 against a fresh Laravel or Symfony application and it will drown you in false positives, because the analyzer does not understand the framework's dynamic features: Eloquent's magic properties and query-builder returns, Laravel's facades, Symfony's service container fetched by string id. The fix is a framework extension that ships the missing type information. For Laravel that is Larastan; for Symfony it is phpstan-symfony. With the extension installed, the analyzer understands Invoice::where('status', ...)->first() returns a nullable Invoice, or that $container->get(InvoiceService::class) returns an InvoiceService, and the false positives disappear so the real findings stand out.

$ composer require --dev phpstan/extension-installer  # auto-discovers PHPStan extensions
$ composer require --dev larastan/larastan  # Laravel: Eloquent, facades, helpers
$ composer require --dev phpstan/phpstan-symfony  # Symfony: container, kernel, console

The automated-fix counterpart to analysis is Rector (introduced in Chapter 5 and central to the upgrades in Chapter 27). Where the analyzer finds problems and stops, Rector rewrites code: it applies type declarations the analysis implies, modernizes old syntax, and performs framework and PHP-version migrations as repeatable rule sets. Analysis and Rector are two halves of the same loop. The analyzer is the inspector that fails the build; Rector is the tool that makes many of the fixes mechanically, so raising a codebase to a higher analysis level is often a Rector run followed by a much shorter manual pass.

18.6 The Unified Quality Gate

Every tool in this part does one job, and their value compounds only when they run together, automatically, on every change. Section 5.5 wired style and a first analysis pass into a composer check script; with the testing depth of Chapter 16, the mutation threshold of Chapter 17, and the analysis and taint checks of this chapter, that script becomes the complete quality gate: a single command that asserts the code is styled, type-correct, secure against the injection classes taint analysis covers, behaviorally tested, and tested well enough to clear a mutation floor, with no known-vulnerable dependencies.

// composer.json: the full gate, each stage one command, all of them under "check"
"scripts": {
    "lint":    "php-cs-fixer fix --dry-run --diff",
    "fix":     "php-cs-fixer fix",
    "analyse": "phpstan analyse",
    "taint":   "psalm --taint-analysis",
    "test":    "pest",
    "mutate":  "infection --threads=max --min-covered-msi=90",
    "audit":   "composer audit",
    "check":   ["@lint", "@analyse", "@taint", "@test", "@mutate", "@audit"]
}

This one command is the contract the whole team and the pipeline share. A developer runs composer check before pushing; the continuous-integration pipeline of Chapter 26 runs exactly the same command on every push and pull request, and a change that fails any stage does not merge. Because the local and CI definitions are identical, "works on my machine" stops being a category of failure. The capstone in Chapter 29 assembles this gate into the end-to-end build as the step that every later chapter assumes is green.

Best practice: order the gate fast-to-slow, and split heavy stages

Run the cheap stages first so the build fails fast: style and static analysis finish in seconds, the unit suite in a few more, and only then the slower integration tests, mutation run, and audit. Mutation testing is the heaviest stage, so a common split is to run it over just the changed files on each pull request (Section 17.3) and the full suite on a nightly schedule, keeping pull-request feedback fast without giving up the full measurement.

Lab 11 · Assemble the Ledger's quality gate

Goal: bring style, static analysis, security taint analysis, tests, and mutation score together into one composer check that gates every change, and watch each stage catch a real defect.

  1. Add phpstan.neon at level 9 over src and tests, generate a baseline if needed, and get composer analyse green. Introduce a deliberate type error (read a property the class lacks) and confirm it fails; fix it.
  2. Add a @template generic to a small TypedCollection as in Section 18.3, then write a line that reads the wrong type out of it and confirm PHPStan reports it without the code being run.
  3. Install Psalm, run vendor/bin/psalm --taint-analysis, and add a controller line that echoes $_GET['note'] directly. Confirm Psalm reports a TaintedHtml flow, then fix it by encoding the output (Chapter 9) and confirm the error clears.
  4. If the Ledger is on a framework, add phpstan/extension-installer plus Larastan or phpstan-symfony and re-run analysis; note how the framework false positives disappear.
  5. Wire the full check script from Section 18.6 (style, analysis, taint, tests, mutation floor, audit). Run it once locally, then make your CI workflow (Chapter 26) run the same composer check and fail the build on any stage.
Exercise 18.1

Give one bug that a unit test would catch but PHPStan at level 9 would not, and one bug that PHPStan would catch but a passing unit suite would not. Then explain why Psalm's taint analysis can flag a cross-site-scripting flaw that neither a unit test nor ordinary type-level static analysis would notice, in terms of what taint analysis tracks that the others do not.

Part VI Running PHP in Production

This is the operations core of the guide, where the application meets the machine. Chapter 19 explains PHP-FPM, the process manager every production PHP deployment runs on, and how to give each site its own isolated pool. Chapter 20 puts a web server in front of it, with complete, security-correct configurations for both nginx and Apache. Chapter 21 packages the whole stack into containers with Podman and Docker. Chapter 22 scales it: OPcache, statelessness, caching, and the path from one box to many. Everything is built on the Grimoire Ledger and tied back to the shared-nothing model from Section 1.3.

Chapter 19PHP-FPM and Per-Site Pools

PHP-FPM (FastCGI Process Manager) is how PHP runs in production.

It maintains a pool of long-lived worker processes that a web server hands requests to over the FastCGI protocol, and it is where you control concurrency, per-site isolation, resource limits, and the security boundary around the PHP runtime. This chapter explains the model, the process-manager tuning that decides how much load you can serve, and the per-site pool design that lets one host run many sites without them being able to read each other's files.

19.1 The FPM Model: Master and Pools

FPM runs as a master process that supervises one or more pools. Each pool is an independent set of worker processes with its own configuration: its own Unix user and group, its own listening socket, and its own resource limits. The web server does not run PHP; it forwards a request describing the script to execute, and an idle worker in the pool runs it under the shared-nothing model (load script, run, respond, reset) and returns to the pool. Because workers are long-lived, the per-request cost of starting PHP is paid once at boot rather than on every request, and the opcode cache (Chapter 22) stays warm across requests in the same worker.

# pool config locations differ by distribution family
# Debian/Ubuntu: /etc/php/8.4/fpm/pool.d/*.conf   (default pool: www.conf)
# RHEL/Fedora:   /etc/php-fpm.d/*.conf            (default pool: www.conf)
# systemctl reload php8.4-fpm  # Debian/Ubuntu service name
# systemctl reload php-fpm  # RHEL/Fedora service name

19.2 The Process Manager: static, dynamic, ondemand

The pm directive chooses how the pool manages its worker count, and it is the main throughput and memory lever. There are three modes. static keeps a fixed number of workers always running (most predictable, best for a dedicated, well-characterized workload). dynamic keeps a floor of spare workers and scales up to a ceiling under load (a good general default). ondemand starts workers only when needed and reaps idle ones (lowest idle memory, best for many low-traffic sites on one host).

The process-manager directives that govern concurrency and memory.
DirectiveApplies toMeaning
pmallstatic, dynamic, or ondemand.
pm.max_childrenallThe hard ceiling on concurrent workers, and therefore on concurrent requests. The single most important number.
pm.start_serversdynamicWorkers started at launch.
pm.min_spare_servers / pm.max_spare_serversdynamicThe idle-worker band FPM maintains so bursts do not wait on process spawning.
pm.process_idle_timeoutondemandHow long an idle worker survives before being reaped.
pm.max_requestsallRecycle a worker after this many requests, bounding the impact of any slow memory leak in the app or an extension.
Standard · Sizing pm.max_children to available memory

The PHP-FPM documentation and operational consensus size pm.max_children from memory, not guesswork: measure the average resident memory of one busy worker, then set the ceiling so that pm.max_children multiplied by that average fits within the RAM you have budgeted for PHP (leaving headroom for the database, cache, and operating system). A ceiling set too high lets a traffic spike drive the host into swap and collapse; set too low, it queues requests and wastes capacity. Confirm the average with the FPM status page under real load rather than assuming.php.net, "FPM Configuration"; the memory-sizing method is the documented operational practice. The formula is roughly: max_children = (RAM available for PHP) / (average worker memory). Re-measure after major application or dependency changes.

19.3 Per-Site Pools: Isolation by User and Socket

The reason to run a separate pool per site is isolation. Each pool runs as its own Unix user, so the operating system's permission model prevents one site's PHP from reading another site's files, sessions, or secrets, even though they share a host. Each pool listens on its own Unix socket, owned by the web server's user so only the web server can talk to it. This is defense in depth: a vulnerability in one application is contained to that application's user, not the whole machine.

; /etc/php/8.4/fpm/pool.d/ledger.conf  --  a dedicated, isolated pool
[ledger]
user  = ledger
group = ledger

; a private Unix socket, readable only by the web server (nginx/apache user)
listen       = /run/php/ledger.sock
listen.owner = www-data
listen.group = www-data
listen.mode  = 0660

pm = dynamic
pm.max_children      = 12
pm.start_servers     = 3
pm.min_spare_servers = 2
pm.max_spare_servers = 4
pm.max_requests      = 500
Standard · Per-site process isolation (OWASP A01; layered with MAC)

Running each site under its own service account is a baseline least-privilege control: it uses the operating system's discretionary access control so a compromise of one application cannot read another's data or code on a shared host. This is layered with, not a replacement for, mandatory access control. On the RHEL family, SELinux additionally confines the FPM process type and labels its files; that confinement is the subject of the companion SELinux volume and should be applied to FPM pools as described there. On the Debian/Ubuntu family the analogous control is AppArmor. Discretionary isolation (the pool user) and mandatory confinement (SELinux/AppArmor) together give two independent layers around the PHP runtime.OWASP Top 10:2025 A01 (Broken Access Control) and the least-privilege principle; the PHP-FPM per-pool user/group directives. For MAC confinement of php-fpm, see the companion volume, "Enforcing, Confining & Hardening with SELinux," and apply AppArmor profiles on Debian/Ubuntu.

19.4 Per-Pool Runtime Hardening

A pool can override php.ini settings for just that site, which is how you apply the Chapter 11 hardening per application. The php_admin_value and php_admin_flag forms set values the application cannot override at runtime, which is what you want for security settings. Use this to confine each pool's filesystem reach with open_basedir, set a pool-specific error log, cap memory, and disable dangerous functions for that site.

; continued in ledger.conf: per-pool hardening the app cannot undo
php_admin_value[open_basedir]      = /srv/ledger:/tmp
php_admin_value[memory_limit]      = 128M
php_admin_value[error_log]         = /var/log/php/ledger-error.log
php_admin_flag[display_errors]     = off
php_admin_flag[log_errors]         = on
php_admin_value[disable_functions] = exec,passthru,shell_exec,system,proc_open,popen,curl_multi_exec

; only execute real .php files, never user-supplied extensions
security.limit_extensions = .php

; kill any request still running after 30s, independent of the app's setting
request_terminate_timeout = 30s

; slow-request log for diagnosing latency
slowlog               = /var/log/php/ledger-slow.log
request_slowlog_timeout = 5s

Two of these deserve emphasis. open_basedir restricts every filesystem function in that pool to the listed paths, so a path-traversal or file-inclusion bug cannot reach /etc or another site's directory. security.limit_extensions ensures FPM only executes files ending in .php, a guard against tricks that try to make it execute an uploaded image or text file as code. Both are per-pool, so each site is confined to exactly what it needs.

19.5 Observing the Pool

FPM exposes a status endpoint and a slow log, both essential for tuning and incident response. The status page reports active and idle workers, the listen-queue depth, and the peak worker count, which is exactly the data you need to size pm.max_children from Section 19.2. The slow log captures a stack trace of any request exceeding request_slowlog_timeout, turning "the site is slow sometimes" into a specific function and line.

; expose status and ping endpoints (restrict access to them in the web server)
pm.status_path = /fpm-status
ping.path      = /fpm-ping
Caution: never expose the FPM status page publicly

The status and ping endpoints reveal internal load and request data and must be reachable only from localhost or an internal monitoring network, enforced in the web-server configuration (Chapter 20). Exposing them publicly is an information-disclosure misconfiguration (OWASP A02:2025). Restrict them with allow/deny exactly as the Chapter 20 templates do, or serve them from a separate localhost-only server block where you want stricter separation.

Lab 12 · Give the Ledger its own hardened FPM pool

Goal: run the Ledger in a dedicated FPM pool as its own user, on a private socket, with per-pool hardening, and confirm the isolation works.

  1. Create a system user ledger with no login shell, and place the app under /srv/ledger owned by that user.
  2. Write ledger.conf in the pool directory as shown, with user = ledger, a private socket owned by the web-server user, the dynamic process manager, and the php_admin_value hardening block.
  3. Reload FPM and confirm a worker is running as ledger with ps -o user,args -C php-fpm.
  4. Prove the open_basedir confinement: from a test script in the pool, try to file_get_contents('/etc/passwd') and confirm it is denied.
  5. Enable the status page, restrict it to localhost in the next chapter's web-server config, and read worker counts under a small load test to estimate the right pm.max_children.
Exercise 19.1

A host has 8 GB of RAM. You budget 4 GB for PHP-FPM, and measurement shows each busy worker averages 80 MB resident. What is a defensible ceiling for pm.max_children, and what happens to the host if you instead set it to 200 and a traffic spike fills every worker? Which FPM endpoint gives you the real average worker memory under load?

Chapter 20Web Servers: nginx and Apache with PHP-FPM

A web server sits in front of FPM to terminate TLS, serve static files efficiently, and reverse-proxy dynamic requests to the pool.

This chapter gives complete, security-correct configurations for both nginx (the modern default) and Apache, including the front-controller routing every framework expects, the one nginx FastCGI pitfall that has caused real remote-code-execution incidents, the security response headers, and the rules that keep your source and secrets unreachable.

20.1 Division of Labor

The web server handles what it is good at: accepting connections, terminating TLS, serving static assets directly from disk, and applying access rules and response headers. Anything that needs PHP, it forwards to the FPM socket from Chapter 19. The universal pattern for a framework application is the front controller: every dynamic request is routed to public/index.php, which the framework's router then dispatches. The web root is public/ and nothing above it is reachable, the layout from Section 3.5.

20.2 nginx + PHP-FPM

nginx does not run PHP itself; it passes matching requests to FPM via fastcgi_pass. The configuration below is the correct, security-aware baseline. Read the comments closely: the try_files line and the exact location ~ \.php$ block are not stylistic, they are the difference between a safe deployment and an exploitable one.

# /etc/nginx/sites-available/ledger.conf
server {
    listen 443 ssl;
    http2 on;
    server_name ledger.example.com;

    root /srv/ledger/public;  # the web root is public/, nothing above it
    index index.php;

    ssl_certificate     /etc/ssl/ledger/fullchain.pem;
    ssl_certificate_key /etc/ssl/ledger/privkey.pem;

    # every non-file URL goes to the front controller (framework routing)
    location / {
        try_files $uri /index.php$is_args$args;
    }

    # execute ONLY the real front controller as PHP; never arbitrary .php by path
    location ~ ^/index\.php(/|$) {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/ledger.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param DOCUMENT_ROOT   $document_root;
        internal;  # only reachable via the try_files rewrite above
    }

    # deny everything else ending in .php (no executing uploads or stray scripts)
    location ~ \.php$ { return 404; }

    # never serve dotfiles, .env, or version control metadata
    location ~ /\.(?!well-known) { deny all; }

    # restrict the FPM status page to localhost
    location = /fpm-status {
        allow 127.0.0.1; deny all;
        include fastcgi_params;
        fastcgi_param SCRIPT_NAME /fpm-status;
        fastcgi_pass unix:/run/php/ledger.sock;
    }
}
Standard · The SCRIPT_FILENAME / cgi.fix_pathinfo pitfall

A long-standing PHP/nginx misconfiguration lets an attacker execute an uploaded non-PHP file as PHP. It arises when nginx passes any URL ending in .php to FPM without confirming the file exists, combined with the legacy cgi.fix_pathinfo=1 behavior, which makes PHP fall back to executing a different file from the path. The defenses are layered and all are required: set cgi.fix_pathinfo=0 in php.ini; route only the known front controller to FPM rather than any .php path (as above); and never store uploads inside the web root. This is the canonical example of why Section 3.5 insists that only public/ is served.PHP Manual, cgi.fix_pathinfo; nginx and FPM deployment guidance. Maps to OWASP Top 10:2025 A02 (Security Misconfiguration) and A05 (Injection). The single most important rule: do not blindly pass $uri to fastcgi_pass for any .php request.

20.3 Apache + PHP-FPM

Apache reverse-proxies to FPM with mod_proxy_fcgi, configured, like the nginx block, so that only the front controller is executed and every other .php path is refused. This replaces the legacy mod_php and gives the same per-user pool isolation as nginx.

# /etc/apache2/sites-available/ledger.conf  (mod_proxy_fcgi enabled)
<VirtualHost *:443>
    ServerName ledger.example.com
    DocumentRoot /srv/ledger/public

    SSLEngine on
    SSLCertificateFile    /etc/ssl/ledger/fullchain.pem
    SSLCertificateKeyFile /etc/ssl/ledger/privkey.pem

    <Directory /srv/ledger/public>
        Require all granted
        AllowOverride None
        DirectoryIndex index.php
        FallbackResource /index.php  # front-controller routing
    </Directory>

    # execute ONLY the front controller as PHP (mirrors the nginx rule)
    <FilesMatch "^index\.php$">
        SetHandler "proxy:unix:/run/php/ledger.sock|fcgi://localhost"
    </FilesMatch>

    # refuse any other .php (uploads, stray scripts) as source or script
    <FilesMatch "^(?!index\.php$).+\.php$">
        Require all denied
    </FilesMatch>

    # expose the FPM status/ping endpoints to localhost only (mirrors the nginx rule)
    <LocationMatch "^/(fpm-status|fpm-ping)$">
        Require local
        SetHandler "proxy:unix:/run/php/ledger.sock|fcgi://localhost"
    </LocationMatch>

    # never serve dotfiles or secrets. FilesMatch matches by filename only; DirectoryMatch
    # also denies files INSIDE dot-directories such as .git/config (but allows .well-known)
    <FilesMatch "^\.">
        Require all denied
    </FilesMatch>
    <DirectoryMatch "/\.(?!well-known)">
        Require all denied
    </DirectoryMatch>
</VirtualHost>
Best practice: keep all of this in central config, not .htaccess

Put access rules and the FPM handler in the server or virtual-host configuration rather than per-directory .htaccess files. Central configuration is faster (Apache does not stat for .htaccess on every request), version-controlled with the rest of your infrastructure, and not editable by a compromised application writing into its own directory. Disable .htaccess override entirely (AllowOverride None) unless a specific dependency requires it.

20.4 Security Response Headers and TLS

The web server is where you add the security response headers that instruct browsers to enforce protections, and where TLS is terminated. These are the same for nginx and Apache in intent; only the syntax differs.

Standard · OWASP Secure Headers and Mozilla Server-Side TLS

The OWASP Secure Headers Project specifies the response headers a hardened site should send: Strict-Transport-Security (force HTTPS), Content-Security-Policy (constrain what the page may load and execute, the strongest defense-in-depth against XSS), X-Content-Type-Options: nosniff, Referrer-Policy, and a restrictive Permissions-Policy. Mozilla's Server Side TLS guidance provides the recommended protocol versions and cipher suites for the TLS configuration; target the "Intermediate" profile unless you can require modern clients only. These controls live at the web-server layer and address OWASP A02:2025 (Security Misconfiguration). Note that a default-src 'self' policy blocks inline <script> and <style> blocks by design; permit a specific inline script with a per-response nonce- value or a sha256- hash rather than weakening the policy with 'unsafe-inline'.OWASP Secure Headers Project; Mozilla Server Side TLS configuration generator. TLS certificate issuance and renewal (for example via ACME) is referenced but not the subject of this guide; see those projects' documentation.

# nginx security headers (add_header in the server block)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; object-src 'none'; frame-ancestors 'self'" always;
# the same headers in Apache (mod_headers), set once at the vhost level
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Content-Security-Policy "default-src 'self'; object-src 'none'; frame-ancestors 'self'"
A note on CORS

Cross-Origin Resource Sharing is the other header family the A02 list flags when it is too permissive. CORS is not a header you simply switch on: Access-Control-Allow-Origin should name the specific origins you trust, never the wildcard * when the endpoint sends credentials (cookies or an Authorization header), and you echo back an allowed origin only after checking it against an allow-list. A same-origin application like the Ledger needs no CORS headers at all; add them only when a different origin must call your API, and scope them as narrowly as the request requires.

Lab 13 · Serve the Ledger through nginx, then Apache

Goal: put a real web server in front of the FPM pool from Lab 12, with safe FastCGI handling, security headers, and protected secrets, and verify the dangerous cases are blocked.

  1. Configure the nginx server block as shown, pointing fastcgi_pass at the Ledger pool socket and root at public/. Reload nginx and load the app over HTTPS.
  2. Attack the FastCGI handling: upload a file named evil.php into a writable directory under the web root (or simulate one) and confirm requesting it returns 404, not execution. Request /.env and confirm it is denied.
  3. Confirm the security headers are present with curl -sI https://ledger.example.com/.
  4. Now reproduce the same deployment with Apache and mod_proxy_fcgi, using the same FPM socket. Confirm identical behavior: front-controller routing works, only .php goes to FPM, dotfiles are denied.
  5. Restrict /fpm-status to localhost and confirm it is unreachable from another host.
Exercise 20.1

Explain, in terms of the front-controller pattern, why routing only /index.php to FPM (rather than any URL ending in .php) prevents an attacker who manages to write a file into the web root from executing it. Why is "never store uploads in the web root" a second, independent layer of the same defense?

Chapter 21Containerizing PHP with Podman and Docker

Containers package PHP, its extensions, your code, and your configuration into one immutable image that runs identically on a laptop, in CI, and in production, eliminating the "works on my machine" gap.

This chapter builds a production-grade container image for the Ledger, explains the choice between Podman and Docker, runs PHP-FPM behind nginx as cooperating containers, and hardens the image and runtime. Where container isolation depends on mandatory access control, it points to the companion SELinux volume.

21.1 Why Containers, and the FPM-in-a-Container Model

A container image is a layered, content-addressed filesystem plus metadata describing how to run it. For PHP the value is parity and immutability: the exact PHP version, extensions, and locked dependencies are baked in, so every environment runs byte-identical code. The standard model keeps PHP-FPM in one container and the web server (nginx) in another, the two communicating over the FastCGI socket or a TCP port, mirroring the separation from Chapter 20. A single-process alternative, FrankenPHP, combines a web server and PHP in one image and is increasingly popular, with the long-running-runtime caveats from Section 14.5.

21.2 Podman or Docker

Both build and run OCI-standard images from the same Dockerfile (a Containerfile in Podman's preferred naming, identical syntax), so images are portable between them. The differences are operational. Docker uses a central daemon running as root; Podman is daemonless and runs containers rootless by default, where the container's "root" maps to an unprivileged user on the host, a meaningful reduction in blast radius. On the RHEL family, Podman is the native, SELinux-integrated default. This guide writes for both and notes where they diverge; the commands are largely interchangeable (podman for docker).

Standard · Container hardening: CIS Docker Benchmark and NIST SP 800-190

The CIS Docker Benchmark and NIST SP 800-190 (Application Container Security Guide) define the consensus controls for container images and runtime: run as a non-root user, use a minimal trusted base image, do not bake secrets into layers, pin base images by digest, scan images for known vulnerabilities, and apply mandatory access control to the running container. On the RHEL family that MAC layer is SELinux, which labels container processes and volume mounts (the :Z / :z volume flags); that mechanism is covered in full by the companion SELinux volume. On the Debian/Ubuntu family the analog is AppArmor, applied via the runtime's default profile.CIS Docker Benchmark; NIST SP 800-190. The PHP-specific application of these (non-root FPM user, no secrets in the image, pinned php base digest) is shown below. For SELinux labeling of container volumes, see the companion volume's container chapter.

21.3 A Production Image for the Ledger

The official php images provide FPM variants per version. A multi-stage build keeps the final image small and free of build tools: one stage installs Composer dependencies, the final stage copies only what runs. The image runs as a non-root user and contains no secrets (those arrive at runtime via environment).

# Containerfile / Dockerfile  --  multi-stage, non-root, no secrets baked in
# ---- build stage: install locked dependencies ----
FROM php:8.4-fpm-alpine AS build
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /app
COPY composer.json composer.lock ./
# install the same ext-* the app declares so Composer's platform check passes in this stage too
RUN docker-php-ext-install pdo_mysql
RUN composer install --no-dev --no-scripts --optimize-autoloader --no-interaction
COPY . .
RUN composer dump-autoload --optimize --no-dev

# ---- runtime stage: only what runs in production ----
FROM php:8.4-fpm-alpine
# install only the extensions the app needs, then harden php.ini
RUN docker-php-ext-install pdo_mysql opcache && \
    mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY docker/php/hardening.ini "$PHP_INI_DIR/conf.d/zz-hardening.ini"
COPY --from=build /app /srv/ledger
WORKDIR /srv/ledger

# run as the unprivileged user the base image already provides
USER www-data
EXPOSE 9000
CMD ["php-fpm", "--nodaemonize"]

Three choices make this production-grade. The build uses the locked dependencies with --no-dev, so no development tools or unpinned versions reach the image (the supply-chain discipline from Section 8.3). It starts from the production php.ini and layers the Chapter 11 hardening on top. It runs as www-data, not root, satisfying the most important CIS control. Because the FPM master itself runs as that unprivileged user here, the per-pool user/group switch from Chapter 19 does not apply inside the container; one application per image simply runs as the container's own user, which is the correct model. If you do carry a pool file into the image, drop its user/group lines, since a non-root master cannot switch worker users and will warn at startup. A .dockerignore excludes .env, .git, and local artifacts so they cannot leak into a layer.

21.4 Running the Stack

The Ledger runs as two cooperating containers, nginx and php-fpm, on a shared network, with the application code and the web root visible to both. Podman expresses this as a pod or with Compose; Docker uses Compose. The web server's config is the one from Chapter 20, with fastcgi_pass pointed at the php-fpm container's name and port 9000.

# bring the stack up (podman and docker accept the same compose file)
$ podman compose up -d  # or: docker compose up -d
$ podman compose ps
Caution: volume labels and rootless mapping on SELinux hosts

On an SELinux-enforcing host, a bind-mounted volume must be labeled for the container to read it, or access is denied. The runtime does this when you append :Z (private label) or :z (shared label) to the volume mount. Omitting it is the most common "permission denied" with containers on the RHEL family, and the wrong fix (disabling SELinux) removes a whole protection layer. The correct handling of volume labels and rootless user mapping is covered in the companion SELinux volume; on Debian/Ubuntu, the AppArmor default profile applies instead and volume labeling is not needed.

Lab 14 · Build and run the Ledger as rootless containers

Goal: produce a hardened, non-root container image of the Ledger and run it behind nginx with Podman (rootless) or Docker.

  1. Write the multi-stage Containerfile and a .dockerignore that excludes .env, .git, vendor/, and tests/.
  2. Build the image and confirm it runs as a non-root user (podman run --rm IMAGE id shows www-data, not root) and that no secret files are present (podman run --rm IMAGE ls -a shows no .env).
  3. Write a compose file with an nginx service and the php-fpm service sharing the app volume; point nginx's fastcgi_pass at php:9000.
  4. Bring the stack up and load the Ledger. On an SELinux host, add :Z to the bind mount and observe the difference; consult the companion SELinux volume for the full labeling treatment.
  5. Scan the image for known vulnerabilities and confirm the base is pinned; record the result as a supply-chain gate.
Exercise 21.1

Name three specific things the multi-stage build keeps out of the final image and why each matters (consider: development dependencies, the Composer binary, secrets, and the .git directory). Then explain why running the container as www-data rather than root limits the damage of a remote-code-execution bug in the application, and which CIS Docker Benchmark control that satisfies.

Chapter 22Scaling PHP

PHP scales unusually well because of the shared-nothing model: with no in-memory state to coordinate, you add capacity by adding workers and machines.

This chapter covers the levers in the order you should pull them: OPcache (the largest single win), genuine statelessness (the precondition for horizontal scale), caching and queues to take load off the request path and the database, and the measurement that tells you what to do next. The Ledger is the subject throughout.

22.1 OPcache: the First and Largest Win

Without an opcode cache, PHP re-parses and re-compiles every script on every request, the dominant cost in a typical request. OPcache, bundled with PHP, stores compiled bytecode in shared memory so that work is done once per worker boot, not once per request. Enabling and tuning it is the highest-leverage change you can make, often several times the throughput of an uncached runtime, for the price of a few directives.

Standard · PHP Manual: OPcache configuration and timestamp validation

The PHP Manual specifies OPcache's key directives. opcache.memory_consumption sizes the shared bytecode cache; opcache.max_accelerated_files must exceed your application's file count (check with find . -name '*.php' | wc -l). The critical production setting is opcache.validate_timestamps=0, which stops OPcache from checking each file's modification time on every request: it removes a filesystem stat per request but means a deploy must explicitly reset the cache (restart or reload FPM, or call opcache_reset()) for new code to take effect. The just-in-time compiler (opcache.jit, with opcache.jit_buffer_size) can further speed CPU-bound code, though typical web workloads benefit less than compute-heavy ones; as of PHP 8.4 its default is disable (it was tracing before), so the template below enables it explicitly.php.net, "OPcache" configuration and the JIT documentation. Set validate_timestamps=0 only with a deploy step that resets OPcache; otherwise new code silently does not deploy. Preloading (opcache.preload) can pin framework classes in memory for a further gain.

; production OPcache settings (php.ini or a conf.d file)
opcache.enable=1
opcache.memory_consumption=192        ; MB of shared memory for bytecode
opcache.max_accelerated_files=20000   ; > the number of .php files in the app
opcache.validate_timestamps=0         ; do not stat files per request (reset on deploy!)
opcache.jit=tracing
opcache.jit_buffer_size=64M
Caution: validate_timestamps=0 means deploys must reset OPcache

With timestamp validation off, editing or deploying a file has no effect until OPcache is cleared. The fix is to make "reload FPM" or "opcache_reset()" a step of your deployment, ideally with an atomic release-directory swap so the cache and the code change together. Forgetting this produces the maddening symptom of a deploy that "did nothing," and is the one OPcache foot-gun everyone meets once.

22.2 Statelessness Is the Scaling Unlock

Horizontal scaling (more than one PHP server behind a load balancer) only works if any server can handle any request, which requires that no request-spanning state lives in a single server's memory or local disk. The two usual offenders are sessions and uploads. By default PHP writes session data to local files; on a multi-server deployment, a user whose next request lands on a different server loses their session. The fix is to move session storage to a shared backend (Redis is the common choice) and to store uploaded files in shared object storage rather than local disk. Once state is external, the PHP tier is purely stateless and scales by replication.

Best practice: externalize sessions before you add a second server

Point session.save_handler at Redis (or use the framework's Redis session driver) and confirm a user stays logged in across servers, before you put a load balancer in front. The alternative, sticky sessions that pin a user to one server, works but undermines the elasticity and fault tolerance that horizontal scaling exists to provide: lose that server and you lose those sessions. Stateless is the better target.

22.3 Caching Layers

Beyond OPcache (which caches compiled code), an application cache stores computed results, and you reach for the PSR-6/PSR-16 cache interfaces from Section 5.3 with a Redis or APCu backend so the implementation is swappable. Cache the expensive and the frequently read: rendered fragments, the results of slow queries, configuration. The ordering of caches, from cheapest to most involved, is OPcache (code), then in-process APCu (per-server data), then shared Redis (cross-server data), then HTTP caching at the edge for cacheable responses. Each layer removes load from the one behind it, and the database is usually the layer you are protecting.

22.4 Move Slow Work off the Request Path

A request should do the minimum needed to respond; anything slow and not needed for the response (sending email, generating the Ledger's invoice PDFs, calling a third-party API, image processing) belongs in a background queue. The web request enqueues a job and returns immediately; a separate pool of worker processes (Laravel queues, Symfony Messenger, both from Part IV) consumes the queue. This keeps request latency low and lets you scale the workers independently of the web tier, which is itself a form of horizontal scaling applied to the slow work.

22.5 The Database Is Usually the Bottleneck

Because the PHP tier scales so easily, the constraint moves to the database, which does not. The defenses are layered: cache reads so they never reach the database; add read replicas to spread read load; index and optimize the queries that actually run (find them with the slow-request log from Section 19.5 and the database's own slow-query log); and watch the connection count, because each FPM worker may hold a connection and pm.max_children times the number of servers can exceed the database's connection limit. Be cautious with persistent database connections under FPM; they can pile up in ways that exhaust the server.

22.6 Measure, Then Scale

Scaling decisions should follow measurement, not intuition. The FPM status page tells you whether you are worker-bound (the listen queue grows, workers are all busy: add workers or servers). Application metrics and a profiler tell you where request time goes. The database's metrics tell you whether it is the wall. The discipline is to find the actual bottleneck before adding capacity, because adding PHP servers in front of a saturated database makes things worse, not better. This closes the loop with the observability controls (centralized logging, OWASP A09) from Section 6.2.

Lab 15 · Tune and scale the Ledger

Goal: enable and verify OPcache, make the application stateless, and observe the effect under load.

  1. Apply the production OPcache settings to the Ledger's runtime and confirm them from the FPM side, not the CLI: php-fpm -i | grep opcache.enable shows the directives, and a script served through the pool reports a warm cache via opcache_get_status(). Checking with plain php -i reports OPcache disabled even on a correctly configured server, because opcache.enable_cli defaults to 0 and the CLI is a different SAPI (Section 11.1). Add an opcache_reset() step (or FPM reload) to your deploy procedure.
  2. Run a small load test (for example with a benchmarking tool) before and after enabling OPcache and record the throughput difference.
  3. Switch session storage to Redis (session.save_handler = redis or the framework driver) and confirm a session survives across two FPM instances by pointing a load balancer at both.
  4. Move the Ledger's invoice-export work into a queued job; confirm the request returns immediately and a worker performs the export.
  5. Drive load until the FPM status page shows the listen queue growing, and decide from the numbers whether to raise pm.max_children, add a server, or address the database. Justify the decision from the metrics.
Exercise 22.1

Explain why PHP's shared-nothing model (Section 1.3) makes horizontal scaling almost free, and what one thing you must do to your session handling first. Then explain the trade-off of opcache.validate_timestamps=0: what does it buy on every request, and what new step does it force into your deployment?

Part VII Operating and Maintaining in Production

Standing an application up is not the same as running it well over time. This part covers the operational disciplines that keep PHP healthy in production once it is live. Chapter 23 moves slow work off the request into background jobs and the workers that run them. Chapter 24 covers the long-running and asynchronous runtimes that trade away shared-nothing simplicity for throughput. Chapter 25 supplies the profiling, metrics, and tracing that turn performance and reliability from guesswork into measurement. Chapter 26 builds the continuous-integration and zero-downtime deployment pipeline that ships every change safely. Chapter 27 confronts the system you inherit rather than the one you wrote: upgrading and maintaining legacy and end-of-life PHP. Every chapter here is applied to the Grimoire Ledger carried through the earlier parts.

Chapter 23Background Processing: Queues, Workers & Scheduled Tasks

A request should do the least work that produces a correct response.

Everything else (sending the invoice email, rendering a PDF, calling a slow third-party API, processing an upload) belongs off the request, in a background job that a separate pool of worker processes runs. Section 22.4 introduced the idea in passing; this chapter builds it properly: how a job queue works, how workers run and stay running under a process supervisor, and the correctness concerns (idempotency, retries, failure handling) that decide whether background work is reliable or a silent source of lost and duplicated effort.

23.1 Why Move Work off the Request

Three payoffs justify the machinery. Latency: the user waits only for what they need, while the slow part happens afterward. Resilience: a slow or failing dependency no longer fails the user's request, because the request already returned. Scalability: workers scale independently of the web tier, so you add capacity exactly where the load is (this is the horizontal scaling of Section 22.4 applied to slow work). The pattern is always the same: the request enqueues a job, a small serializable message describing work to be done, and returns immediately; a worker process dequeues and executes it later.

23.2 Queues and Workers in the Frameworks

A queue is a backend that holds jobs until a worker takes them: Redis, a database table, or a dedicated broker such as Amazon SQS or RabbitMQ. You rarely build this yourself, because both frameworks from Part IV provide it. Laravel's queue system and Symfony's Messenger component each give you a job or message class, a dispatch call that enqueues it, and a long-running worker command (php artisan queue:work, php bin/console messenger:consume) that processes it, along with serialization, multiple named queues, priorities, and delays.

Best practice: enqueue identifiers, not stateful objects

A job is executed later, possibly seconds or minutes after it was dispatched, by a different process, and the data it touches may have changed in between. Put an identifier in the job (the invoice number), not a serialized copy of the domain object, and re-load the current state inside the worker. This keeps the job small, avoids stale data, and respects the shared-nothing instinct from Section 1.3: the worker starts from the database, not from a frozen snapshot smuggled through the queue.

23.3 Keeping Workers Running

A worker is a long-running CLI process, so something must start it, restart it when it exits, and run the right number of copies as the right user. The two standard supervisors are a systemd service unit and Supervisor (supervisord); both restart a worker that dies and run it under a dedicated, least-privilege account, exactly as the FPM pool does in Chapter 19. Because a worker holds your code in memory for its whole life, two operational rules follow. New code does not take effect until workers restart, so restarting them is a deployment step (the same hazard, and fix, as the OPcache reset in Section 22.1). And a worker should be recycled after a bounded number of jobs or minutes (the framework's --max-jobs / --max-time options, the analog of FPM's pm.max_requests) so any slow memory growth in the app or a dependency cannot accumulate without limit.

# /etc/systemd/system/ledger-worker.service  -- supervise a queue worker
[Unit]
Description=Ledger queue worker
After=network.target

[Service]
User=ledger
Group=ledger
ExecStart=/usr/bin/php /srv/ledger/artisan queue:work --max-time=3600 --tries=3
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target

23.4 Correctness: Idempotency, Retries, and Failures

The hard part of background work is not running a job, it is running it reliably when things go wrong. A job can run more than once: a transient failure triggers a retry, or a worker does the work and then crashes before it acknowledges completion, so the queue redelivers it. Therefore a job must be idempotent, meaning running it twice has the same effect as running it once. Make it so explicitly: check whether the invoice email was already sent before sending it, or key the side effect on a unique token. Pair that with bounded retries and exponential backoff for transient failures, a maximum attempt count, and a dead-letter destination (Laravel's failed_jobs table, a Messenger failure transport) where exhausted jobs land for inspection instead of retrying forever or vanishing.

Caution: "I only dispatch it once" is not a guarantee of single execution

At-least-once delivery is the normal behavior of real queues, so a job you dispatch a single time can still execute more than once whenever a worker fails after the side effect but before the acknowledgement. Designing for exactly-once by hoping it never double-runs is how duplicate charges and duplicate emails happen. Assume at-least-once delivery and make the work idempotent; that assumption, not the dispatch count, is what makes background processing safe.

23.5 Scheduled Tasks

Recurring work (a nightly report, a cleanup sweep, overdue-invoice reminders) is the time-based sibling of queued work. The operating-system mechanism is cron, but the modern pattern is a single cron entry that runs the framework's scheduler once a minute (php artisan schedule:run, or Symfony's Scheduler), with the actual schedule defined in version-controlled code rather than scattered across crontab lines on individual servers. On a multi-server deployment, guard against a task running once per server when it should run once total, using the framework's run-on-one-server lock or a shared lock; this is the same statelessness discipline from Section 22.2 applied to scheduled work.

Lab 16 · Move the Ledger's slow work into a queue

Goal: take a slow operation off the request, run it under a supervised worker, and prove it behaves correctly when it runs twice or fails.

  1. Turn the Ledger's invoice-export (or email) into a queued job that carries only the invoice number, and dispatch it from the controller so the request returns immediately.
  2. Run the worker under systemd or Supervisor as the ledger user; confirm it restarts after you kill it.
  3. Make the job idempotent (record that the export ran, and skip if it already did); dispatch it twice and confirm the side effect happens once.
  4. Configure three retries with backoff and a failed-jobs destination; force a failure and confirm the job lands there for inspection rather than disappearing or looping.
  5. Add an overdue-reminder task to the framework scheduler and wire the single schedule:run cron entry; on a two-server setup, confirm it runs once, not twice.
Exercise 23.1

Describe a concrete sequence in which a job you dispatched exactly once executes twice, and name the property that makes that safe. Then explain why a queue worker must be restarted on every deploy, connecting it to the same reason OPcache must be reset in Section 22.1.

Chapter 24Long-Running and Asynchronous Runtimes

Chapter 19 and Chapter 21 run PHP under FPM, where every request starts from a clean slate, the shared-nothing model of Section 1.3. A newer class of application servers keeps the PHP application booted in memory and serves many requests per worker, paying the framework bootstrap cost once instead of on every request and delivering large throughput gains.

Section 14.5 named them; this chapter is the depth: how RoadRunner, Swoole, and FrankenPHP differ, what Laravel Octane adds on top, the performance you gain, and the new correctness model you take on, because the very thing that makes these runtimes fast (persistent memory between requests) is exactly the thing that turns a harmless habit into a cross-request bug.

24.1 The Model Shift

Under FPM the per-request cost includes booting the framework every time: the autoloader, configuration, the service container, compiled routes. For a heavy framework that bootstrap can dominate an otherwise fast request. A long-running runtime boots the application once and then loops, handling request after request in the same process with everything already in memory. The gain is the elimination of per-request bootstrap; the cost is that state now survives from one request to the next inside a worker, so you must reset it or avoid creating it. This reframes Section 1.3 usefully: shared-nothing was never a law of the language, it was a property of the FPM SAPI, and these runtimes opt out of it on purpose.

24.2 The Runtimes

Three runtimes dominate, and they sit at different points on the invasiveness scale. RoadRunner is an application server written in Go that manages a pool of PHP worker processes and dispatches requests to them through a fast protocol; your code runs a small worker loop and it needs no PHP extension. Swoole (and its community fork Open Swoole) is a PHP extension that adds coroutine-based asynchronous I/O and a built-in HTTP server to the language itself; it is the most powerful and the most invasive, because getting the most from it means writing to its async model. FrankenPHP is a modern application server built on the Caddy web server with PHP embedded, written in Go; it runs in a classic mode that is a drop-in FPM replacement needing no application changes, or a worker mode that keeps the application in memory.

Standard · FrankenPHP and the PHP Foundation

FrankenPHP appeared in 2022, reached 1.0 in late 2023, stabilized through 2024 and 2025, and is an officially supported PHP Foundation project, which makes it a credible production choice rather than an experiment. Its worker mode boots the application once and answers subsequent requests in milliseconds; its classic mode requires no code changes at all. Both Laravel and Symfony provide the integration needed to reset framework state between requests when running in worker mode.frankenphp.dev (documentation and worker mode); the PHP Foundation's project list. RoadRunner (roadrunner.dev) and Swoole / Open Swoole (the Swoole and openswoole.com projects) are the other two production runtimes; all three are OCI-deployable alongside the container model of Chapter 21.

24.3 Laravel Octane and the Framework On-Ramp

Laravel Octane is not itself a server; it runs a Laravel application on top of FrankenPHP, Swoole or Open Swoole, or RoadRunner, supplying the worker loop and, critically, the hooks that reset framework state between requests so you do not have to reset it by hand. It is the low-friction on-ramp for Laravel teams that want the throughput without rebuilding their mental model from scratch. Symfony offers an equivalent path through its runtime component, which targets RoadRunner and FrankenPHP. In both cases the framework handles most of the reset; what it cannot handle is your own state and the assumptions of third-party libraries, which is the subject of the next section.

24.4 The New Correctness Model

The defects these runtimes introduce are precisely the ones FPM hid. A static property or a singleton that accumulates per-request data now leaks one user's data into a later user's request in the same worker. An unclosed file handle, database connection, or registered event listener accumulates across thousands of requests as a memory leak. A container that caches a request-scoped service hands a stale one to the next request. The frameworks reset most of this for you, but your own static mutable state, and libraries written on the assumption of a fresh process per request, are yours to audit.

Caution: the persistence that makes it fast is the bug surface

This is not hypothetical. A session leak in FrankenPHP's worker mode was a real security vulnerability, fixed in a later release, in which the feature that keeps state in memory between requests caused one request's session to bleed into another. Treat the move to a long-running runtime as taking on a new class of defect: audit for static mutable state, globals, unclosed resources, and request-scoped singletons; lean on the runtime's documented reset hooks; recycle workers after a bounded number of requests to cap any leak; and keep the runtime itself patched, because its bugs now live in a process that handles many requests rather than one.

24.5 When to Adopt

The default remains FPM. It is simpler, its correctness model is free because every request starts clean, and most web applications are I/O-bound, spending the request waiting on the database or an external service, where removing the bootstrap helps least. Reach for a long-running runtime when measurement (the profiling in the performance chapter) shows that bootstrap or CPU time, not I/O, is your bottleneck, when the throughput gain is worth taking on the new defect class, and when the team can invest in the discipline the model demands. It is a deliberate trade made on evidence, not a free upgrade you apply by default.

Lab 17 · Run the Ledger on a long-running runtime, and meet the new failure mode

Goal: serve the Ledger from a persistent runtime, measure the gain, and reproduce then fix the cross-request state bug that defines this model.

  1. Run the Ledger under FrankenPHP worker mode (or Laravel Octane on the runtime of your choice) and confirm it serves requests.
  2. Benchmark requests per second against the FPM deployment from earlier in Part VI and record the difference.
  3. Introduce a bug on purpose: a static counter or array that accumulates per request. Hit the endpoint repeatedly and observe the state surviving across requests, where under FPM it would have reset.
  4. Fix it by removing the static state or using the runtime's reset hook, and confirm each request is again independent.
  5. Set a worker recycle limit (a maximum number of requests per worker) and explain, in one sentence, what class of problem that bounds.
Exercise 24.1

Explain, in terms of Section 1.3, why a static property that was completely harmless under FPM becomes a cross-request data leak under a long-running runtime. Then: given an application that spends 80% of each request waiting on the database, would switching to a long-running runtime produce a large throughput gain? Justify the answer in terms of where the time actually goes.

Chapter 25Performance & Observability

Chapter 22 ended on a rule: scale from measurement, not intuition.

This chapter is the measurement. It covers the three different lenses you need (profiling, metrics, and tracing, which answer different questions), the deeper OPcache and JIT tuning that turns the largest single performance lever all the way up, and the observability endpoints that let a load balancer and an operator see whether the application is actually healthy. Optimizing without these is guessing; this chapter replaces the guess with evidence.

25.1 Three Lenses: Profiling, Metrics, Tracing

Three tools answer three different questions, and you need all three. Profiling shows where time and memory go inside a single request, function by function; it is how you find the hot path, and you run it in development or staging. Metrics are aggregate numbers over time (requests per second, latency percentiles, error rate, worker saturation); they run in production and tell you that something is wrong and roughly where. Tracing follows one request across the services it touches; it tells you which hop in a distributed path is slow. Confusing them wastes effort: a profiler will not tell you your p99 latency in production, and a metrics dashboard will not tell you which function is slow.

25.2 Profiling: Find the Hot Path Before You Touch It

The cardinal rule is to optimize from a profile, never from a hunch, because the slow part is rarely where intuition points. Xdebug includes a profiler that is thorough but heavy, suited to local investigation. For staging and sampled production use, dedicated profilers such as Blackfire and Tideways, or the open-source SPX extension, impose far less overhead and can sample live traffic. You read the profile to find the function or query that dominates, fix that, and re-profile to confirm the win moved.

Caution: never leave Xdebug enabled on a production runtime

Xdebug, and especially its profiler, imposes a large performance penalty by design, and an enabled debugger on a production server is also an attack surface. It belongs in development. Leaving it loaded in production is both a severe slowdown and a security misconfiguration (OWASP A02:2025); confirm it is absent from the production runtime exactly as you confirm display_errors = Off in Chapter 11.

25.3 OPcache and JIT, Tuned Deeper

Section 22.1 established OPcache as the first and largest win. Two further levers build on it. Preloading (opcache.preload) loads and links your framework's core classes into shared memory once at server start, so they are never loaded per request again, at the cost of a server restart to pick up code changes. The just-in-time compiler (opcache.jit) compiles hot code paths to machine code; it can meaningfully speed CPU-bound work, but the typical web request is I/O-bound and benefits little, so the JIT is a measure-then-enable feature rather than an automatic win. Both reward the profiling discipline above: turn them on, measure, and keep them only if the numbers move.

25.4 Metrics: Watch the Percentiles

In production you cannot profile every request, so you watch aggregate metrics: request rate, error rate, the saturation of the FPM pool (the status page from Section 19.5) and of any queue (the worker chapter), and above all latency. Expose these from the application to a time-series system; the common open standard is Prometheus, scraping a /metrics endpoint a PHP client library produces. Watch latency as percentiles, not averages: a healthy-looking mean of 80 ms can hide a p99 of two seconds that a meaningful fraction of users actually experience, and the average is exactly the statistic that conceals the worst case you most need to see.

25.5 Distributed Tracing with OpenTelemetry

When a request fans out across services, a trace shows the whole path and where the time went. OpenTelemetry is the vendor-neutral standard for this, and it has a PHP implementation.

Standard · OpenTelemetry for PHP

OpenTelemetry (OTel) is the vendor-neutral standard for traces, metrics, and logs, with a defined wire protocol (OTLP) so any compliant backend can receive the data. The PHP implementation's tracing, metrics, and logs signals are all stable per the project's status page (retrieved June 2026); individual instrumentation packages vary in maturity, so check a package's own stability note before depending on it. The SDK instruments a request and propagates trace context to downstream services, and auto-instrumentation packages exist for the major frameworks.opentelemetry.io, the PHP documentation and the per-signal status page (all three signals stable, retrieved June 2026). This closes the observability loop opened by the centralized-logging guidance (OWASP A09) in Section 6.2.

25.6 Health and Readiness Endpoints

A load balancer or container orchestrator needs to know which instances to send traffic to, and that requires the application to report its own health. Expose two cheap endpoints: a liveness check that confirms the process is up and responding, and a readiness check that confirms it can actually serve, by verifying its real dependencies are reachable (the database, the cache) and that startup work (such as migrations) is done. The orchestrator restarts an instance that fails liveness and routes traffic away from one that fails readiness, which is what lets the stateless tier of Section 22.2 add and drain instances without dropping requests. Keep both endpoints inexpensive and reachable only from the internal network.

Lab 18 · Measure the Ledger, then improve it on evidence

Goal: use each of the three lenses on the running Ledger, make one evidence-driven improvement, and expose the endpoints an orchestrator needs.

  1. Profile a deliberately slow endpoint with a profiler, identify the dominant cost, fix it, and re-profile to confirm the hot path moved.
  2. Expose a Prometheus /metrics endpoint and record request rate, error rate, and a latency histogram; report the p95 and p99, and contrast them with the mean.
  3. Add OpenTelemetry tracing to one request path and view the resulting trace.
  4. Enable opcache.preload for the framework, measure the change, and keep it only if the numbers justify it.
  5. Add /health (liveness) and /ready (readiness, checking the database and cache) endpoints, and confirm /ready fails when you stop the database.
Exercise 25.1

Explain why you should optimize from a profile rather than intuition, with a one-line example of a "fix" that intuition suggests but a profile would reject. State the difference between a liveness and a readiness check and why a load balancer specifically needs readiness. Finally, explain why a service can have an excellent average latency and still be failing a meaningful share of its users, and which statistic exposes that.

Chapter 26Continuous Integration and Deployment

Everything built so far has to reach production safely and repeatably, on demand, without downtime, and with a way back if it goes wrong.

This chapter assembles the delivery pipeline: continuous integration that runs the same checks you run locally and refuses to merge a red build, a release artifact that is exactly what was tested, an atomic zero-downtime deploy with instant rollback, database migrations sequenced so they are safe to apply and to reverse, and the supply-chain gates that ensure you know precisely what shipped.

26.1 The Pipeline: Integration Before Delivery

Continuous integration runs on every push and pull request, and it runs the very checks you already run by hand: the composer check aggregate of style, static analysis, and tests from Section 5.5 and Section 6.4, plus composer audit from Section 8.3. A build that fails any stage does not merge, full stop. Continuous delivery then takes a green commit to production through automated, repeatable steps. The entire purpose of the pipeline is a single guarantee: what runs in production is identical to what was tested, with no manual step in between where drift can enter.

26.2 Build the Artifact Once

Deploy what you tested, not a fresh resolution of it. The production build runs composer install --no-dev --optimize-autoloader (the locked versions from Section 3.2, no development tools) and compiles any assets, and the strong form is to build that result once into an immutable artifact, a container image from Chapter 21 or a versioned archive, and then promote that same artifact through staging to production. Promoting one artifact, rather than rebuilding at each stage, removes the possibility that staging and production differ because they were assembled at different moments from different dependency resolutions.

26.3 Zero-Downtime, Atomic Releases

The deployment technique that gives both zero downtime and instant rollback is the atomic symlink release. Each release is unpacked into its own timestamped directory, fully prepared there (dependencies in place, migrations run, caches warmed), and only then does a single current symlink flip to point at it; the next request FPM serves runs the new release, and nothing was ever served from a half-updated directory. Rollback is the same flip in reverse, back to the previous release directory, which is why it is effectively instant. Shared, persistent paths (uploads, logs) live outside the release directories and are symlinked in. The common PHP tool that implements this pattern is Deployer.

# the atomic-release layout: prepare a new release, then flip one symlink
/srv/ledger/
├── releases/
│   ├── 2026-06-04-101500/  # fully prepared before it is ever served
│   └── 2026-06-04-094500/  # the previous release; rollback target
├── shared/  # persistent data symlinked into each release
│   ├── .env
│   └── storage/
└── current -> releases/2026-06-04-101500  # the atomic switch
Caution: with validate_timestamps=0, the deploy must reset OPcache

Because production OPcache runs with opcache.validate_timestamps=0 (Section 22.1), new code does not take effect until the cache is cleared, and long-running queue workers (the background chapter) and any persistent runtime (the async chapter) hold old code in memory until restarted. Make resetting OPcache (a reload of FPM, or an opcache_reset()) and restarting workers explicit steps of the symlink flip, so the code, the bytecode cache, and the workers all change together. Forgetting this is the deploy that "did nothing."

26.4 Migrations in the Deploy

Schema changes (the migrations from the Databases chapter) run as a step of the deploy, not by hand on a production database. Their ordering relative to the symlink flip matters, and the safe default is expand-then-contract: a release adds new schema and code that tolerates both the old and new shape, and only a later release removes the old shape, so that at no instant does running code require schema that does not exist, and a rollback never needs data a migration already destroyed. Apply additive, backward-compatible migrations before the flip; defer destructive ones to a subsequent release once the new code is proven.

26.5 Supply-Chain Gates

The pipeline is also where supply-chain integrity is enforced, the application of Section 8.3's A03 discipline at the moment of shipping. Run composer audit as a build gate so a newly disclosed vulnerability in a pinned dependency fails the build rather than reaching production silently. Pin the container base image by digest and scan it (Chapter 21). And generate a software bill of materials (an SBOM, in a standard format such as CycloneDX) for each release, so you hold a precise inventory of every component you shipped and can answer, the day a vulnerability is disclosed, whether you are affected.

Standard · Supply-chain integrity in the pipeline (OWASP A03:2025)

OWASP Top 10:2025 A03, Software Supply Chain Failures, expands the former Vulnerable and Outdated Components category to the whole supply chain, and the deployment pipeline is where the controls are enforced: build from a committed lockfile and never resolve anew in production (Section 3.2), gate on composer audit (Section 8.3), pin and scan base images (Chapter 21), and produce an SBOM as a release artifact. Together these turn the supply chain from an unknown into an inventory you can audit.OWASP Top 10:2025 A03 (Software Supply Chain Failures); CycloneDX and SPDX are the common SBOM formats. The build-once-and-promote and atomic-release practices here are the operational consensus reflected in tools such as Deployer and in the container model of Chapter 21.

Lab 19 · Build a pipeline and deploy the Ledger with zero downtime

Goal: gate merges on the full check suite, deploy the Ledger with an atomic release, prove rollback, and produce a supply-chain inventory.

  1. Configure CI to run composer check and composer audit on every push, and confirm a deliberately failing test or a flagged dependency blocks the merge.
  2. Deploy the Ledger using the timestamped-release-plus-current-symlink layout; include an FPM reload (OPcache reset) and a worker restart in the flip.
  3. Run a database migration as a deploy step, and verify the application is never served from a half-migrated state.
  4. Roll back by flipping the symlink to the previous release, and confirm the site returns to the prior version immediately.
  5. Generate a CycloneDX SBOM for the release and add composer audit as a gate that fails the build on a known vulnerability.
Exercise 26.1

Explain why a deploy runs composer install rather than composer update, and why building one artifact and promoting it beats rebuilding per environment. Describe how the atomic symlink flip delivers both zero downtime and instant rollback. Finally, explain why opcache.validate_timestamps=0 forces an explicit OPcache reset into the deployment procedure.

Chapter 27Upgrading and Maintaining Legacy and EOL PHP

Not every PHP system you meet is one you built.

Sooner or later you inherit one: a server still answering requests on a version that left support years ago, with no lockfile, no tests, and nobody who remembers how it works. This chapter is the procedure for that moment. It covers establishing exactly what you have, the safe path from an end-of-life runtime to a supported one (a sequence of small, verified version steps rather than one blind leap), the tools that do most of the mechanical work, and the harder question of what to do when you genuinely cannot upgrade yet without leaving the system exposed.

27.1 What "End of Life" Actually Means

The support calendar from Section 1.1 is the starting point: each PHP branch gets two years of active support and two more of security-only fixes, four years in total, and then it is end of life. End of life is not "old but fine." It means that from that date forward, a newly disclosed vulnerability in that runtime is never patched by the PHP project; it simply stays open. An EOL runtime therefore does not hold steady, it degrades: every month that passes is another month of publicly known, unfixed flaws in the layer that runs all of your code. That is an OWASP Top 10:2025 A03 (Software Supply Chain Failures, which in 2025 absorbed the former Vulnerable and Outdated Components category) exposure at the most fundamental level, the language runtime itself.

Standard · Upstream EOL is not always the whole story: check for vendor backports

There are two support clocks, and confusing them leads to both false alarm and false comfort. The PHP project's own clock is the one in Section 1.1; when a branch passes it, upstream ships no further fixes. But enterprise Linux distributions (the RHEL family, Debian and Ubuntu LTS) frequently backport security fixes to the PHP version they shipped for the supported life of that operating-system release, so a distro-packaged PHP can still be receiving patches after its upstream EOL date. Before you classify a runtime as dangerously unsupported, confirm which clock applies: a self-compiled or third-party-repo PHP past upstream EOL is genuinely unpatched, while a distro package may still be maintained by the vendor. Either way the version is aging out and must be planned off, but the urgency differs.php.net, "Supported Versions" (upstream lifecycle); your distribution's security-update policy (for example the RHEL Application Streams lifecycle, or the Debian and Ubuntu LTS support windows) for backport coverage. When the two conflict, the distro's backport status governs whether you are currently receiving fixes; the upstream date governs how long the vendor will keep doing so.

27.2 Assess Before You Touch Anything

The first move is never to change the system; it is to understand it, on a copy. Snapshot the server (the throwaway-system rule from the front matter applies with double force here: the legacy box is often the only copy, and there is no rebuild script). Then inventory the runtime: php -v for the CLI version, the FPM version separately because they can differ (Chapter 11), php -m for the loaded extensions, and php --ini for where configuration lives. Inventory the code next: is there a composer.json and a lockfile, a test suite, version control at all? Each "no" is both a risk and a thing you will add as part of the work.

With the target chosen (a currently supported branch from Section 1.1), measure the gap statically before running anything. The PHPCompatibility ruleset for PHP_CodeSniffer scans a codebase against a declared target version and reports every construct that will break, without executing the code, which turns "will this run on 8.4?" into a concrete, reviewable list.

# scope the breakage statically: check the code against a target version
$ composer require --dev phpcompatibility/php-compatibility
$ vendor/bin/phpcs --standard=PHPCompatibility --runtime-set testVersion 8.4- legacy/
Best practice: write a characterization test before you change behavior

A legacy app usually has no tests, which is exactly why changing it is frightening. Before upgrading, capture the current behavior of the critical paths as a few high-level tests (record the inputs and the outputs the live system produces, and assert them). These "characterization tests" do not judge whether the behavior is correct; they pin what it currently does, so that when the upgrade changes something you find out from a red test rather than from a customer. They are the safety net Chapter 6 argued for, retrofitted onto code that never had one.

27.3 Upgrade One Step at a Time

The wrong way to cross a decade of releases is in a single leap from, say, 5.6 to 8.4: that stacks every backward-incompatible change from every intervening version into one enormous, undebuggable change set. The right way is incremental, major version by major version (and across the 7.x and 8.x minors where breakage warrants), running the test suite or your characterization tests at each stop and committing a known-good state before the next. PHP documents the breaking changes for every version in a dedicated migration appendix, so each step has a definitive checklist.

Standard · PHP Manual: per-version "Backward Incompatible Changes"

The PHP Manual ships a "Migrating from X to Y" appendix for every release, whose "Backward Incompatible Changes" section is the authoritative list of what an upgrade to that version can break. Working through them in order is the supported upgrade path. A 5.x application will meet the largest of these early: the original ext/mysql (the mysql_* functions) was removed in PHP 7.0 in favor of PDO or mysqli (Chapter 9), the unsafe register_globals and magic_quotes were already gone as of 5.4, and constructs such as create_function() and each() were removed in 8.0. Many of these removals are the same unsafe defaults Section 1.1 describes, so a substantial part of the application's historical attack surface closes simply by reaching a modern runtime.php.net Manual, the "Appendices: Migrating from PHP X to PHP Y" series and each version's "Backward Incompatible Changes." Read the appendix for every version you pass through, not only the endpoints.

27.4 Let the Tools Do the Mechanical Work

Most of the edits an upgrade requires are mechanical and automatable, which is the job of Rector (introduced in Chapter 5). Pointed at a target version through a level set, Rector rewrites outdated syntax and removed-function usage into the modern equivalent across the whole codebase. The disciplined loop is: PHPCompatibility to scope the work, Rector to perform the bulk transformation to the next version, then PHPStan or Psalm (Chapter 5) and your tests to verify nothing regressed, committing at each version before moving on.

// rector.php  --  drive the codebase up to a target PHP version
<?php
use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\LevelSetList;

return RectorConfig::configure()
    ->withPaths([__DIR__ . '/src'])
    ->withSets([LevelSetList::UP_TO_PHP_84]);  // apply every upgrade rule through 8.4
Caution: automated rewrites still need review and tests

Rector is fast and largely correct, but it is editing code whose behavior you may not fully understand yet, so treat its output as a proposed change, not a finished one: read the diff, run the tests or characterization tests, and commit one version step at a time so that if a regression appears you can bisect it to a single, small transformation. Applying a multi-version jump in one unreviewed run reintroduces exactly the undebuggable-change-set problem the step-by-step path exists to avoid.

27.5 When You Cannot Upgrade Yet

Sometimes the upgrade cannot happen immediately: a critical extension or dependency has no version compatible with a supported runtime, or the work is not yet funded. That does not make the EOL runtime safe; it makes it a risk you must actively contain rather than quietly accept. The compensating controls are the defense-in-depth layers from Section 8.4, applied harder precisely because the runtime underneath is unpatched: isolate the host on the network and restrict its outbound access; put a maintained reverse proxy or web application firewall in front of it; apply the runtime and per-pool hardening from Chapter 11 and Chapter 19 in full; and confine the process with mandatory access control (Section 19.3, SELinux or AppArmor). Then write the risk down: record what is unpatched, what controls compensate, who accepted the risk, and the date by which it will be resolved.

Caution: compensating controls buy time, they do not remove the risk

Network isolation, a WAF, and aggressive hardening reduce the exposure of an unpatched runtime; none of them closes a vulnerability in the runtime itself, because the flawed code is still executing. Treat these measures as a deliberately time-boxed bridge to the upgrade, with a deadline attached, not as a permanent home for an EOL system. An EOL runtime with compensating controls is a managed risk; an EOL runtime with no plan is an incident that has not happened yet.

27.6 Upgrade in Place, or Rebuild?

The last question is strategic. Upgrading the runtime fixes the runtime's vulnerabilities; it does nothing for application-level flaws that the old code is riddled with, because string-built SQL, unencoded output, and trusting-the-client habits are insecure on PHP 8.4 exactly as they were on 5.6 (Part III). So weigh the path honestly. If the codebase is reasonably structured and its breakage is mechanical, a runtime upgrade driven by Rector is the cheap, high-value move. If the application is small, or so unsafe and unstructured that you would be auditing every line anyway, rebuilding it on a current framework (Part IV) behind the same external contract is often the better investment, because the framework supplies the Part III defenses you would otherwise have to retrofit by hand. The common middle path is to do both in sequence: upgrade the runtime first to stop the bleeding (close the unpatched-runtime hole that is the most urgent risk), then modernize the application incrementally behind that now-supported runtime.

Lab 20 · Assess and plan an upgrade for a legacy snapshot

Goal: take an end-of-life PHP snapshot from unknown to a concrete, evidence-backed upgrade plan, and perform one verified version step, without ever risking the only copy.

  1. On a disposable VM, stand up an older runtime (PHP 7.4 is a convenient EOL example) and a small script that uses a construct removed later, such as create_function() or each(). Record php -v, php -m, and where the ini files live.
  2. Install PHPCompatibility and run it with --runtime-set testVersion 8.4-; read the report as your scoped list of breakage.
  3. Add a characterization test that pins the script's current output, so you can detect any behavior change during the upgrade.
  4. Configure Rector with the level set up to your target and apply it; review the diff line by line, then run the characterization test and PHPStan. Commit the result.
  5. For any item PHPCompatibility flagged that you cannot resolve (a dependency with no compatible release, say), write the compensating-control note from this chapter's isolation guidance, with an explicit remediation deadline.
Exercise 27.1

A server runs PHP 7.2, which is past its upstream end of life, but it is the PHP packaged by a still-supported enterprise Linux release that backports security fixes. Is the runtime "unsupported"? Explain the difference between upstream EOL and vendor backport support, how you would confirm which one applies to this server, and why "the distro still patches it" changes the urgency of the upgrade but not the eventual need for it.

Part VIII Standards & Compliance Reference

This part consolidates every standard cited through the guide into a single reference you can hand to an auditor or use as a self-assessment, and it is honest about where authoritative guidance for PHP simply does not exist. Chapter 28 states that gap plainly, then maps the controls this guide teaches to the PHP-FIG standards, the OWASP Top 10:2025 and ASVS 5.0, and the benchmarks that govern the surrounding stack, with the full master crosswalk in Appendix C.

Chapter 28Compliance and Standards Reference

An auditor will ask which standards your PHP application meets and how you verify it. This chapter answers that, starting with an uncomfortable but important fact: there is no government or industry security benchmark for the PHP language itself, the way there is for an operating system or a web server.

This chapter explains what that means, names the authorities that do apply, and maps the guide's controls to verifiable requirements.

28.1 The Honest Gap: No STIG or Benchmark for PHP Itself

Standard · There is no DISA STIG or CIS Benchmark for the PHP language

Unlike operating systems (which have CIS Benchmarks and DISA STIGs) and web servers (the CIS nginx and Apache Benchmarks), the PHP language and runtime have no dedicated DISA STIG or CIS Benchmark as of June 2026. This is a real gap, and it is stated here rather than papered over. The authoritative substitutes this guide relies on are the OWASP PHP Configuration Cheat Sheet and the broader OWASP Cheat Sheet Series for runtime and application hardening, the PHP Manual's Security chapter for the language's own guidance, and the OWASP ASVS 5.0 for verifiable application-security requirements. Where a control genuinely needs a benchmark, the closest applicable ones govern the surrounding stack: the CIS Benchmarks for the operating system, web server, and container runtime, and NIST SP 800-190 for containers.Verified June 2026: no PHP-specific STIG or CIS Benchmark exists. Hierarchy when sources differ: a formal standard (NIST, ASVS) over an industry benchmark (CIS) over a community cheat sheet (OWASP Cheat Sheets) over a framework default. For application web servers and containers, apply the existing CIS Benchmarks; for the PHP runtime, apply the OWASP PHP Configuration baseline from Chapter 11.

The practical consequence is that "PHP compliance" is assembled from three layers, each with its own authority: the operating system and web server are covered by their CIS Benchmarks and STIGs; the PHP runtime is hardened against the OWASP PHP Configuration Cheat Sheet (Chapter 11); and the application is verified against OWASP ASVS 5.0. No single document covers all three, which is exactly why this consolidation chapter exists.

28.2 The PHP-FIG Standards Crosswalk

The coding and interface standards that govern how the code is written, consolidated with where each is applied in the guide.

PHP-FIG standards, status as of June 2026, and where this guide applies them.
StandardStatusApplied in
PSR-1 Basic Coding StandardAccepted (required base of PER-CS)5.2
PSR-12 Extended Coding StyleAccepted, superseded by PER-CS for active use5.2
PER Coding Style 3.0Current living style standard5.2, 5.5
PSR-4 AutoloadingAccepted (supersedes PSR-0)3.4
PSR-3 Logger InterfaceAccepted6.2
PSR-7 / 15 / 17 / 18 HTTP messages, middleware, factories, clientAccepted5.3, frameworks
PSR-11 Container InterfaceAccepted5.3, 12, 13
PSR-6 / 16 CachingAccepted22.3
PSR-14 Event DispatcherAccepted5.3

28.3 OWASP: Top 10:2025 and ASVS 5.0

The Top 10 is an awareness document (the risk categories from Chapter 8); ASVS is the verifiable requirements standard you actually audit against. They are complementary: map a risk to the ASVS requirements that verify it is handled.

Standard · OWASP Application Security Verification Standard 5.0

OWASP ASVS 5.0.0 (released May 2025) is the current verifiable application-security standard, comprising roughly 350 requirements across 17 chapters, organized into verification levels of increasing rigor (Level 1 for basic assurance, Level 2 for most applications handling sensitive data, Level 3 for the highest-assurance systems). Unlike the Top 10, ASVS is written as testable requirements ("verify that..."), which is what makes it suitable as an audit and procurement baseline. Use the Top 10 to communicate risk and ASVS to verify coverage; choose a target level based on the data the application handles.OWASP Application Security Verification Standard 5.0.0 (owasp.org, May 2025). The 17 chapters cover, among others, authentication, session management, access control, validation and encoding, cryptography, error handling and logging, and configuration, which align directly with this guide's Part III.

28.4 The Surrounding Stack

The benchmarks that do exist apply to everything around PHP, and a compliant PHP deployment applies them to that surrounding stack.

Benchmarks and standards for the layers around the PHP runtime.
LayerAuthorityGuide chapter
Operating systemCIS Benchmark and DISA STIG for the distributionhost setup throughout
Mandatory access control (RHEL family)SELinux (companion volume); the DISA STIG requires enforcing mode19.3, 21
Mandatory access control (Debian/Ubuntu)AppArmor profiles19.3, 21
Web serverCIS nginx Benchmark, CIS Apache Benchmark; OWASP Secure Headers; Mozilla TLS20
ContainersCIS Docker Benchmark; NIST SP 800-19021
PHP runtimeOWASP PHP Configuration Cheat Sheet; PHP Manual Security chapter (no STIG/CIS exists)11
ApplicationOWASP ASVS 5.0; OWASP Top 10:2025Part III

The full control-by-control crosswalk, mapping each control to its standard and to the chapter that implements it, is Appendix C. That table is designed to be handed to an auditor directly.

Exercise 28.1

An auditor asks, "Which CIS Benchmark did you apply to PHP?" Write a two-sentence answer that is honest about the gap and names what you applied instead at the runtime layer and at the application layer. Then, for the risk "passwords could be exposed in a breach," name the OWASP Top 10:2025 category, the guide chapter, and the kind of ASVS requirement you would expect to verify it.

Capstone

The final chapter assembles every layer of the guide into one annotated build: the Grimoire Ledger taken from an empty directory to a hardened, containerized, horizontally scalable deployment, with each step labeled by the chapter that explains it and a verification table at the end. Nothing here is new; it is the whole book applied once, in order, so you can see how the layers fit.

Chapter 29Building a Hardened, Scalable PHP Application

This capstone is a checklist with reasons: the end-to-end procedure to take the Grimoire Ledger to production correctly.

Each step cites the chapter that justifies it, so the build is also a review. Run it on a disposable host or in containers; at the end you have a deployment that is standards-compliant at every layer you control.

29.1 The Target Architecture

The finished Ledger is a stateless PHP application served by a dedicated, hardened PHP-FPM pool behind a web server that terminates TLS and sends security headers, packaged as a non-root container, with sessions and cache in Redis and uploads in object storage so the PHP tier replicates freely behind a load balancer. The database sits behind the application with read replicas and a query cache, and writes are transactional. Slow work runs on supervised background workers; the application exposes health and readiness endpoints and is measured and traced in production; and it reaches that production through a continuous-integration pipeline and an atomic, zero-downtime deploy. Every request enters one front controller; every secret arrives from the environment; every error is logged and none is displayed.

29.2 The Build, Step by Step

The end-to-end build. Each step names the chapter that explains it.
#StepFrom
1Initialize a Composer project with PSR-4 autoloading and the standard public/-only layout; commit composer.lock.Ch 3
2Model the domain with typed, immutable value objects and enums (Money, InvoiceStatus); enable strict_types everywhere.Ch 2, Ch 4
3Add the quality toolchain and keep composer check green: PER style, PHPStan static analysis, a unit suite with real assertions, a mutation-score floor, Psalm taint analysis, and composer audit as a supply-chain gate.Ch 5, Ch 16–18, 8.3
4Add structured PSR-3 logging to stderr; route errors to logs, never to users.Ch 6
5Build the data layer on PDO: prepared statements, transactional writes, hydration into the typed domain, and versioned schema migrations.Ch 7
6Defend input and output: validate at the boundary, parameterize every query, encode all output for its context, and add CSRF tokens.Ch 9
7Implement authentication with password_hash, hardened sessions, and libsodium where data must be encrypted; keep secrets in the environment.Ch 10
8Harden the runtime: production php.ini (errors logged not shown, expose_php off, resource limits, session flags, dangerous functions disabled, cgi.fix_pathinfo=0).Ch 11
9Choose and build on a framework (Laravel or Symfony) so routing, escaping, CSRF, validation, and authorization are framework-provided.Part IV
10Expose the read and write paths as a JSON API with correct status codes, machine-readable problem+json errors, and token authentication.Ch 15
11Run the app in a dedicated FPM pool as its own user, on a private socket, with per-pool open_basedir and php_admin_value hardening.Ch 19
12Front it with nginx (or Apache), routing only the front controller to FPM, denying dotfiles, sending security headers, terminating TLS.Ch 20
13Package as a multi-stage, non-root container with no secrets baked in and a pinned base; apply MAC (SELinux/AppArmor) to the runtime.Ch 21
14Tune OPcache; externalize sessions and uploads to Redis and object storage; load-test and size pm.max_children from measurement.Ch 22
15Move slow work off the request into idempotent queued jobs run by supervised, least-privilege workers.Ch 23
16Instrument the app: a profiler in staging, production metrics with latency percentiles, distributed tracing, and health and readiness endpoints.Ch 25
17Ship through CI (the full check suite plus composer audit) and an atomic, zero-downtime deploy that resets OPcache, runs migrations, and produces an SBOM.Ch 26
18Verify against the standards crosswalk and record the result.Ch 28, App C

29.3 Verification

A build is not done until each control is verified, not merely configured. This table is the acceptance test for the deployment.

Capstone verification: how to confirm each control actually holds.
ControlHow to verify
Code is above the web rootRequest /composer.json and /.env; both return 404/denied.
No errors displayedTrigger an exception; the browser shows a generic page, the detail is in the log.
PHP version not advertisedcurl -sI shows no X-Powered-By header.
SQL injection closedAn invoice lookup with ' OR '1'='1 matches nothing.
XSS closedA stored <script> note renders as inert text.
CSRF enforcedA state-changing POST without a valid token is rejected.
Passwords hashed correctlyStored hashes begin with a bcrypt/argon2id identifier, never a raw digest.
Session cookie hardenedThe cookie shows Secure, HttpOnly, SameSite=Lax.
Pool isolationFPM workers run as the site user; open_basedir blocks reads outside the app.
Only the front controller executesA planted .php file in the web root returns 404, not execution.
Container runs non-rootid inside the container is not root; no secrets in the image.
OPcache activeThe FPM status / opcache_get_status() shows a warm cache; deploy resets it.
Stateless tierA session survives a request served by a different server.
Writes are atomicAn invoice and its line items either all persist or, on a forced mid-write failure, none do.
API errors are machine-readableA bad API request returns the right status code and an application/problem+json body, never HTML.
Background jobs are idempotentA job dispatched and run twice produces the same result as running it once.
Health and readiness respond/ready fails when the database is stopped; the load balancer drains that instance.
Deploy is zero-downtime and reversibleA release flips atomically and resets OPcache; rolling back restores the prior release immediately.

When every row passes, the Grimoire Ledger is what this guide set out to build: a PHP application created from nothing, written to the standards the ecosystem agreed on, secured against the OWASP Top 10, hardened at the runtime, served by isolated FPM pools behind a correctly configured web server, containerized without privilege, and able to scale horizontally because it kept faith with the shared-nothing model from the very first chapter.

Exercise 29.1

Run the verification table against your own Ledger build. For any row that fails, find the chapter in the build table (Section 29.2) that addresses it and fix it. Then pick one control and trace it all the way down: the OWASP category it mitigates (Chapter 8), the code or config that implements it, and the command that proves it. That trace, repeated for every control, is what an audit is.

Appendices

Five reference appendices, each designed to stand alone during a deployment or an incident: annotated configuration templates ready to adapt, a deployment and hardening checklist, the standards crosswalk master table for audits, a glossary, and the authoritative references.

Appendix A · Annotated Configuration Templates

Copy-ready, commented templates consolidating the configurations built in the guide. Adapt paths, version numbers, and limits to your environment; the comments explain what each block does and which chapter justifies it. These are starting points to understand and tune, not values to apply blindly.

A.1 Hardened php.ini (production)

; production hardening overlay -- place in a conf.d file loaded by FPM (Chapter 11)
; error handling: log everything, display nothing
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php/error.log
error_reporting = E_ALL

; information disclosure and remote-code surface
expose_php = Off
allow_url_include = Off
allow_url_fopen = Off  ; if no remote URLs are fetched via file functions
enable_dl = Off
cgi.fix_pathinfo = 0  ; critical with nginx/FPM (Section 20.2)

; resource limits (tune to the app)
memory_limit = 128M
max_execution_time = 30
post_max_size = 8M
upload_max_filesize = 2M
max_input_vars = 1000

; disable dangerous functions an app does not need (verify against dependencies)
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_multi_exec

; session security (Section 11.6)
session.cookie_secure = On
session.cookie_httponly = On
session.cookie_samesite = Lax
session.use_strict_mode = On
session.use_only_cookies = On
; sid_length / sid_bits_per_character: leave at defaults (deprecated in PHP 8.4)

; OPcache (Chapter 22): reset on deploy because validate_timestamps is off
opcache.enable = 1
opcache.memory_consumption = 192
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 0

A.2 PHP-FPM Pool (per-site, isolated)

; /etc/php/8.4/fpm/pool.d/ledger.conf  (Chapter 19)
[ledger]
user  = ledger
group = ledger
listen       = /run/php/ledger.sock
listen.owner = www-data
listen.group = www-data
listen.mode  = 0660

pm = dynamic
pm.max_children      = 12  ; size from measured worker memory (Section 19.2)
pm.start_servers     = 3
pm.min_spare_servers = 2
pm.max_spare_servers = 4
pm.max_requests      = 500

php_admin_value[open_basedir]      = /srv/ledger:/tmp
php_admin_value[memory_limit]      = 128M
php_admin_value[error_log]         = /var/log/php/ledger-error.log
php_admin_flag[display_errors]     = off
php_admin_flag[log_errors]         = on
php_admin_value[disable_functions] = exec,passthru,shell_exec,system,proc_open,popen,curl_multi_exec
security.limit_extensions = .php
request_terminate_timeout = 30s
slowlog = /var/log/php/ledger-slow.log
request_slowlog_timeout = 5s
pm.status_path = /fpm-status

A.3 nginx Server Block

# /etc/nginx/sites-available/ledger.conf  (Chapter 20)
server {
    listen 443 ssl;
    http2 on;
    server_name ledger.example.com;
    root /srv/ledger/public;
    index index.php;

    ssl_certificate     /etc/ssl/ledger/fullchain.pem;
    ssl_certificate_key /etc/ssl/ledger/privkey.pem;

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Content-Security-Policy "default-src 'self'; object-src 'none'; frame-ancestors 'self'" always;

    location / { try_files $uri /index.php$is_args$args; }

    location ~ ^/index\.php(/|$) {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/ledger.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param DOCUMENT_ROOT   $document_root;
        internal;
    }
    location ~ \.php$ { return 404; }
    location ~ /\.(?!well-known) { deny all; }
    location = /fpm-status {
        allow 127.0.0.1; deny all;
        include fastcgi_params;
        fastcgi_param SCRIPT_NAME /fpm-status;
        fastcgi_pass unix:/run/php/ledger.sock;
    }
}

A.4 Apache Virtual Host (mod_proxy_fcgi)

# /etc/apache2/sites-available/ledger.conf  (Chapter 20)
<VirtualHost *:443>
    ServerName ledger.example.com
    DocumentRoot /srv/ledger/public

    SSLEngine on
    SSLCertificateFile    /etc/ssl/ledger/fullchain.pem
    SSLCertificateKeyFile /etc/ssl/ledger/privkey.pem

    Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
    Header always set X-Content-Type-Options "nosniff"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Header always set Content-Security-Policy "default-src 'self'; object-src 'none'; frame-ancestors 'self'"

    <Directory /srv/ledger/public>
        Require all granted
        AllowOverride None
        DirectoryIndex index.php
        FallbackResource /index.php
    </Directory>
    <FilesMatch "^index\.php$">
        SetHandler "proxy:unix:/run/php/ledger.sock|fcgi://localhost"
    </FilesMatch>
    <FilesMatch "^(?!index\.php$).+\.php$">
        Require all denied
    </FilesMatch>
    # FPM status/ping to localhost only (mirrors the nginx rule)
    <LocationMatch "^/(fpm-status|fpm-ping)$">
        Require local
        SetHandler "proxy:unix:/run/php/ledger.sock|fcgi://localhost"
    </LocationMatch>
    # deny dotfiles AND files inside dot-directories (.git/config), allow .well-known
    <FilesMatch "^\.">
        Require all denied
    </FilesMatch>
    <DirectoryMatch "/\.(?!well-known)">
        Require all denied
    </DirectoryMatch>
</VirtualHost>

A.5 Containerfile and .dockerignore

# Containerfile / Dockerfile  (Chapter 21)
FROM php:8.4-fpm-alpine AS build
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /app
COPY composer.json composer.lock ./
# install the same ext-* the app declares so Composer's platform check passes in this stage too
RUN docker-php-ext-install pdo_mysql
RUN composer install --no-dev --no-scripts --optimize-autoloader --no-interaction
COPY . .
RUN composer dump-autoload --optimize --no-dev

FROM php:8.4-fpm-alpine
RUN docker-php-ext-install pdo_mysql opcache && \
    mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY docker/php/hardening.ini "$PHP_INI_DIR/conf.d/zz-hardening.ini"
COPY --from=build /app /srv/ledger
WORKDIR /srv/ledger
USER www-data
EXPOSE 9000
CMD ["php-fpm", "--nodaemonize"]
# .dockerignore  -- keep secrets and cruft out of the build context
.git
.env
.env.*
vendor
tests
node_modules
*.md

Appendix B · Deployment & Hardening Checklist

A pre-flight checklist for a production PHP deployment. Each item names the chapter that explains it. Treat any unchecked item as a release blocker until justified.

B.1 Code and Dependencies

B.2 Application Security

B.3 Runtime and Server

B.4 Containers and Scale

B.5 Operations and Delivery

Appendix C · Standards Crosswalk Master Table

The consolidated control-to-standard-to-chapter map. This table is designed to be handed to an auditor: each row names a control, the authoritative standard behind it, the OWASP Top 10:2025 category it mitigates (where applicable), and the chapter that implements it.

Master crosswalk: controls, standards, OWASP 2025 category, and implementing chapter.
ControlAuthorityOWASP 2025Chapter
Code above the web root; only public/ servedOWASP PHP Config; framework conventionA023, 20
Coding style enforced (PER / PSR-12, PSR-1)PHP-FIG PER Coding Style 3.0n/a5
Automated test suite, verified for strength by mutation testingPHPUnit / Pest; Infection (Mutation Score Indicator)n/a16, 17
Static analysis and security taint analysis in the CI quality gatePHPStan rule levels; Psalm security analysis; OWASPA0518
PSR-4 autoloading; PSR-3/7/11 interfacesPHP-FIG PSR-4, PSR-3, PSR-7, PSR-11n/a3, 5, 6
Locked, audited dependencies; install not updateSemVer 2.0.0; Composer; OWASPA033, 8
Prepared statements for all SQLOWASP SQL Injection Prevention; PHP Manual PDOA059
Context-aware output encodingOWASP XSS PreventionA059, 12, 13
CSRF synchronizer tokens; SameSite cookiesOWASP CSRF PreventionA019, 10
Safe file-upload handling (type by inspection, stored outside web root)OWASP File Upload Cheat Sheet; PHP ManualA05, A089
Password hashing (password_hash, Argon2id/bcrypt)OWASP Password Storage; PHP ManualA04, A0710
Login rate-limiting, lockout, and MFAOWASP Authentication Cheat Sheet; ASVS 5.0A0710
Session regeneration; hardened cookie flagsOWASP Session Management; PHP ManualA0710, 11
Secure randomness and vetted crypto (Sodium)PHP Manual (random_bytes, Sodium)A0410
No unserialize() on untrusted inputPHP Manual security warningA089
Errors logged, never displayed; generic error pagesOWASP PHP Config; PHP ManualA10, A026, 11
Runtime hardening (php.ini: expose_php, limits, disabled funcs)OWASP PHP Configuration Cheat SheetA0211
Per-site FPM pool isolation (own user, open_basedir)Least privilege; PHP-FPM docsA0119
MAC confinement of FPM and containersSELinux (companion); AppArmor; DISA STIG (enforcing)A0119, 21
Safe FastCGI handling (front controller only, fix_pathinfo=0)PHP Manual; nginx/FPM guidanceA02, A0520
Security response headers; TLSOWASP Secure Headers; Mozilla Server Side TLSA0220
Container image hardening (non-root, no secrets, pinned, scanned)CIS Docker Benchmark; NIST SP 800-190A02, A0321
Centralized, tamper-evident logging of security eventsOWASP; twelve-factor loggingA096, 25
Transactional data integrity (atomic writes; schema migrations)PHP Manual (PDO transactions); ACIDA087
Machine-readable API errors; API versioningIETF RFC 9457 (Problem Details); OpenAPI SpecificationA1015
Idempotent background jobs; supervised, least-privilege workersFramework queue docs; operational practiceA0423
Cross-request state isolation in long-running runtimesFrankenPHP / RoadRunner / Octane runtime docsA0124
Profiling, metrics, distributed tracing, health and readinessOpenTelemetry; PrometheusA0925
CI/CD quality and supply-chain gates; zero-downtime deploy; SBOMOWASP (A03); CycloneDX SBOMA0326
Run a supported (non-EOL) runtime; safe version upgradesphp.net Supported Versions; per-version migration guidesA0327
Verifiable application requirementsOWASP ASVS 5.0all28
On the PHP-runtime gap

As stated in Section 28.1, there is no DISA STIG or CIS Benchmark for PHP itself. The runtime rows above are therefore anchored to the OWASP PHP Configuration Cheat Sheet and the PHP Manual, which are the authoritative substitutes; the operating-system, web-server, and container rows use their existing CIS Benchmarks and NIST guidance. Where a hierarchy applies, a formal standard outranks an industry benchmark, which outranks a community cheat sheet, which outranks a framework default.

Appendix D · Glossary

Active Record
A persistence pattern (used by Eloquent) in which a model class both represents a database row and carries the methods to load and save it. Concise for table-shaped data. Contrast with Data Mapper.
Autoloading
The mechanism by which referencing a class causes PHP to load the file that defines it, with no manual require. The ecosystem standard mapping is PSR-4.
Composer
PHP's dependency manager. Resolves package version constraints, installs exact versions, and generates the autoloader. composer.json declares intent; composer.lock pins exact resolved versions.
Container (OCI image)
A layered, content-addressed filesystem plus run metadata that packages an application and its runtime to run identically everywhere. Built from a Dockerfile/Containerfile, run by Docker or Podman.
Data Mapper
A persistence pattern (used by Doctrine) in which a plain domain object is kept ignorant of storage and a separate mapping layer handles persistence. More ceremony, cleaner domain model. Contrast with Active Record.
FastCGI
The protocol a web server uses to forward a request to a persistent application process. PHP-FPM speaks FastCGI to nginx or Apache.
Front controller
A single entry-point script (public/index.php) through which every dynamic request passes and is then dispatched by the application's router. The pattern every modern PHP framework uses.
OPcache
PHP's bundled opcode cache. Stores compiled bytecode in shared memory so scripts are not re-parsed on every request. The single largest performance lever for production PHP.
PER (PHP Evolving Recommendation)
A versioned, living PHP-FIG specification, in contrast to a frozen PSR. PER Coding Style 3.0 is the current coding style, superseding PSR-12.
PHP-FIG
The PHP Framework Interop Group, the community body that publishes the PSR and PER specifications enabling interoperability between independent PHP projects.
PHP-FPM
FastCGI Process Manager, the production SAPI for PHP. Runs a master process supervising pools of long-lived worker processes that the web server hands requests to.
Pool (FPM)
An independently configured set of FPM worker processes with its own Unix user, listening socket, and resource limits. Running one pool per site gives operating-system-level isolation between sites.
Prepared statement
A database query whose structure is sent separately from its parameter values, so user data can never be interpreted as SQL. The primary defense against SQL injection.
PSR (PHP Standard Recommendation)
A numbered, accepted PHP-FIG specification. Coding-style PSRs make code uniform; interface PSRs (PSR-3, PSR-7, PSR-11) define shared contracts so libraries interoperate.
SAPI (Server API)
The interface binding the PHP engine to a host. CLI runs scripts; PHP-FPM serves web requests; the built-in server is for development; mod_php is the legacy Apache embedding.
Shared-nothing
PHP's execution model: every request starts from a clean state and everything is destroyed when it ends. State between requests must live in external storage. This model is why PHP scales horizontally so easily.
strict_types
The per-file declaration declare(strict_types=1) that makes PHP enforce declared scalar types exactly, throwing a TypeError on mismatch instead of silently converting. Enabled in every file in this guide.
Static analysis
Examining code without running it to prove properties (types, null-safety, reachability). PHPStan and Psalm are the leading PHP analyzers, graded in strictness levels.
Type juggling
PHP's automatic conversion between types in loose operations, the source of historical comparison bugs. Mitigated by identity comparison (===) and strict_types.
Value object
A small, immutable object defined entirely by its values (for example Money). Built with readonly properties; operations return new instances rather than mutating.

Appendix E · References

All references below are primary or authoritative sources: the PHP project, PHP-FIG, OWASP, NIST, CIS, and the framework projects. For living documents (OWASP, Mozilla, framework docs) the URL points to the current version; verify the version before relying on a specific value.

IdentifierDocumentURL / Location
PHP-MANUALPHP Manual, including the Language Reference and the Security chapter. The PHP Group.https://www.php.net/manual/en/
PHP-VERSIONSPHP Supported Versions and release-cycle policy. Retrieved June 2026 (PHP 8.5 current; 8.2 to 8.5 supported).https://www.php.net/supported-versions.php
PHP-FPMPHP Manual, "FPM Configuration" (process manager, pools, per-pool directives).https://www.php.net/manual/en/install.fpm.configuration.php
PHP-OPCACHEPHP Manual, "OPcache" configuration and the JIT documentation.https://www.php.net/manual/en/book.opcache.php
PHP-SODIUMPHP Manual, "Sodium" cryptography extension; random_bytes, random_int.https://www.php.net/manual/en/book.sodium.php
FIG-PSRPHP-FIG PHP Standard Recommendations index (PSR-1, PSR-3, PSR-4, PSR-7, PSR-11, PSR-12, and others).https://www.php-fig.org/psr/
FIG-PERPHP-FIG PER Coding Style 3.0 (current coding style; supersedes PSR-12).https://www.php-fig.org/per/coding-style/
COMPOSERComposer documentation (versions and constraints, the lockfile, autoloading).https://getcomposer.org/doc/
SEMVERSemantic Versioning 2.0.0.https://semver.org/
OWASP-T10OWASP Top 10:2025, Open Worldwide Application Security Project.https://owasp.org/Top10/2025/
OWASP-ASVSOWASP Application Security Verification Standard 5.0.0 (May 2025).https://owasp.org/www-project-application-security-verification-standard/
OWASP-CSOWASP Cheat Sheet Series (PHP Configuration, SQL Injection Prevention, Cross-Site Scripting Prevention, CSRF Prevention, Password Storage, Session Management, File Upload, Authentication).https://cheatsheetseries.owasp.org/
OWASP-SHOWASP Secure Headers Project. Living document.https://owasp.org/www-project-secure-headers/
MOZ-TLSMozilla Server Side TLS configuration guidance. Living document.https://wiki.mozilla.org/Security/Server_Side_TLS
CIS-BENCHCIS Benchmarks (Linux distributions, nginx, Apache HTTP Server, Docker). Center for Internet Security.https://www.cisecurity.org/cis-benchmarks
NIST-800-190NIST Special Publication 800-190, Application Container Security Guide, 2017.https://doi.org/10.6028/NIST.SP.800-190
RFC-9457IETF RFC 9457, Problem Details for HTTP APIs (obsoletes RFC 7807).https://www.rfc-editor.org/rfc/rfc9457.html
OPENAPIOpenAPI Specification (3.1 and 3.2) for describing HTTP APIs.https://spec.openapis.org/
LARAVELLaravel documentation and release notes (Laravel 13, March 2026; requires PHP 8.3+).https://laravel.com/docs/
SYMFONYSymfony documentation and release process (Symfony 8.1 current; 7.4 LTS).https://symfony.com/doc/current/
DOCTRINEDoctrine ORM documentation (Data Mapper, entities, migrations).https://www.doctrine-project.org/projects/orm.html
PHPSTANPHPStan static analysis documentation (analysis levels).https://phpstan.org/
PSALMPsalm static analyzer and security taint analysis (sources, sinks, escapers).https://psalm.dev/docs/security_analysis/
PHPUNITPHPUnit testing framework documentation.https://phpunit.de/documentation.html
PESTPest testing framework (runs on PHPUnit; datasets, expectations, architecture testing).https://pestphp.com/
INFECTIONInfection mutation-testing framework (Mutation Score Indicator, CI thresholds).https://infection.github.io/
PCOVPCOV code-coverage driver (line coverage; the fast alternative to Xdebug for coverage).https://github.com/krakjoe/pcov
CS-FIXERPHP-CS-Fixer documentation (PER/PSR-12 rule sets).https://cs.symfony.com/
MONOLOGMonolog, the PSR-3 logging implementation.https://github.com/Seldaek/monolog
OTEL-PHPOpenTelemetry for PHP (traces, metrics, logs; per-signal stability status).https://opentelemetry.io/docs/languages/php/
PODMANPodman documentation (rootless, daemonless OCI containers).https://docs.podman.io/
SELINUX-VOLCompanion volume: Enforcing, Confining & Hardening with SELinux, The Programmer's Grimoire. For mandatory access control confinement of PHP-FPM and containers on the RHEL family.See the SELinux edition (selinux/index.html) in this series.

Errata and Updates

This guide is corrected continuously, and you are part of how that happens. If you find an error, a claim that no longer matches its primary source, a command that does not behave as printed, or anything that has simply gone stale, report it to [email protected]. Name the section, and where you can, the authority that settles it; that is exactly how the book is verified in the first place, and a good report can go straight into the next revision.

The current, corrected version always lives at https://gregvogt.net/grimoire/. Each edition was correct as of the revision date printed on its cover, and claims nothing beyond it: standards move, packages update, and the page in front of you ages from the day it ships. When a detail matters, check it against the latest revision there, and against the primary source it cites, before you rely on it.

How to Cite This Guide

Because this is a living document, cite the revision you used and where you found it, so that a reader can retrieve the same text you saw. The revision is printed on the cover.

Vogt, Greg. Creating, Hardening & Scaling PHP. The Programmer’s Grimoire. Revision v1.9-RC1 · June 2026. https://gregvogt.net/grimoire/php/

For LaTeX and reference managers:

@misc{grimoire-php,
  author  = {Vogt, Greg},
  title   = {Creating, Hardening \& Scaling PHP},
  series  = {The Programmer's Grimoire},
  edition = {Revision v1.9-RC1 · June 2026},
  year    = {2026},
  url     = {https://gregvogt.net/grimoire/php/}
}

License and Reuse

The Programmer’s Grimoire is published free of charge and licensed to you under a Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0). You are free to read, copy, share, and adapt or translate it, in any medium or format, for any non-commercial purpose, on one condition: give appropriate credit to the author, link to the license, and indicate whether you changed anything. You may not use the material for commercial purposes. The full terms are at https://creativecommons.org/licenses/by-nc/4.0/.

The intent is plain. The knowledge is meant to be free for anyone to read, copy, and translate, and the non-commercial term is what keeps it that way, so that no one else fences it off or resells it. A paid edition, where one exists, comes from the author and exists only to support the work; the knowledge itself is not the thing being sold.

Trademark and brand. The name The Programmer’s Grimoire, the series wordmark, and the look and branding of these guides are trademarks of Greg Vogt and are not part of the content license above. Reusing the licensed text, including in a translation, grants no right to the Grimoire name or brand. You may not present your version as an official Grimoire, use the name or wordmark to label, endorse, or promote a derivative or third-party work, or otherwise imply that the author stands behind it. Credit the original by name, which is the attribution the license requires, but publish your version under your own title.

Colophon

Each guide is a single HTML document with an external stylesheet and a small progressive-enhancement script, and no inline style or script at all, so it satisfies a strict Content-Security-Policy. Three formats are built from that one source: the PDF with WeasyPrint, the EPUB with EbookLib (parsed with BeautifulSoup), and the Kindle AZW3 with Calibre’s ebook-convert. What you read on screen, on paper, and on an e-reader is the same text rendered three ways.

The reading text is set in Georgia, with the bundled Literata as the press fallback; display headings, numerals, and labels are set in Cinzel, code and the interface in JetBrains Mono (with a bundled fallback face for full glyph coverage), and the Grimoire wordmark in UnifrakturCook. On screen the reader can switch the prose to Atkinson Hyperlegible or OpenDyslexic, scale the type, adjust line spacing, and toggle dark mode; the print and e-reader builds stay in the typeset faces. The bundled fonts are under the SIL Open Font License.

How it was made is described in the notes at the front, and is the point as much as the prose. First drafts are generated by an AI (Claude, made by Anthropic) and then verified, line by line, against primary sources by a human before anything ships. Every factual claim is tracked in a per-volume claims ledger and re-checked against the living standards on each revision, which is why a guide carries a revision date, and why that date is load-bearing.