Table of Contents
3. Request Lifecycle — What Happens During a Request
Why the request lifecycle matters
To understand PHP, you must understand its rhythm.
Every PHP script lives inside a request, and that request defines:
- when code starts
- when it stops
- what state exists
- what disappears
- what can be cached
- what must be rebuilt
AI often generates code that assumes a long‑running environment.
PHP is the opposite: everything begins and ends inside the request.
This page gives you the shape of that lifecycle.
1. The request arrives
A request reaches the server through:
- Apache,
Nginx,
PHP‑FPM,
CLI invocation (for jobs or scripts)
The server hands the request to PHP, which starts with a clean slate:
- no variables,
no objects,
no memory,
no persistent state
Every request is a fresh world.
2. PHP loads the entry script
This is usually:
index.php,
a front controller (in frameworks),
a specific script (in older apps)
PHP begins executing the file top‑to‑bottom, registering declarations and running code as it encounters it.
This is where:
- autoloaders are registered
- configuration is loaded
- routing begins
- dependencies are created
The architecture takes shape here.
3. The application runs
Inside the request, PHP:
- reads input (GET, POST, cookies, headers)
- loads classes on demand
- executes business logic
- interacts with databases
- renders templates
- produces output
Everything that happens, happens inside this one request.
There is no background memory. No persistent objects. No long‑lived services.
This is the heart of PHP’s simplicity.
4. Output is sent to the client
PHP sends output:
- immediately, or
- through output buffering
This includes:
- HTML,
JSON,
files,
headers,
redirects
Once output is sent, it cannot be “unsent”.
This is why mixing logic and output can cause subtle bugs
—
especially when headers are involved.
5. The request ends
When the script finishes:
- all variables are destroyed
- all objects are freed
- all memory is released
- all connections are closed
- all state disappears
The next request starts from zero again.
This is the heart of PHP’s mental model.
Why this matters for AI‑generated code?
AI often assumes:
- persistent services
- global caches
- long‑running workers
- in‑memory state
- background tasks
Your understanding of the request lifecycle helps you spot these mismatches instantly
—
and correct them before they become architectural problems.
- Next: Scope and Lifetime
