Bird
Raised Fist0
PHPprogramming~15 mins

PHP process model per request - Deep Dive

Choose your learning style10 modes available
Overview - PHP process model per request
What is it?
PHP process model per request means that each time a web server receives a request for a PHP page, it starts a fresh process to run the PHP code. This process loads the script, executes it from top to bottom, sends the output back to the user, and then ends. No data or state is kept between requests unless explicitly saved outside the process.
Why it matters
This model exists to keep web applications simple and secure by isolating each request. Without it, one request could accidentally affect another, causing bugs or security risks. It also means PHP scripts always start with a clean slate, which helps developers avoid complex state management.
Where it fits
Before learning this, you should understand basic web servers and how PHP scripts run. After this, you can learn about PHP session management, persistent storage, and advanced performance techniques like opcode caching or long-running PHP processes.
Mental Model
Core Idea
Every PHP request runs in a brand-new process that starts fresh, runs the script, sends output, and then ends, leaving no memory of previous requests.
Think of it like...
It's like a chef who cooks a meal from scratch for each customer, cleans the kitchen completely after, and never remembers what was cooked before.
┌───────────────┐
│ Web Server    │
└──────┬────────┘
       │ HTTP Request
       ▼
┌───────────────┐
│ PHP Process   │
│ (new each req)│
│ Load Script   │
│ Execute Code  │
│ Send Output   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Client Browser│
Build-Up - 6 Steps
1
FoundationWhat happens on a PHP request
🤔
Concept: Introducing the basic flow of a PHP script execution per request.
When a user visits a PHP page, the web server receives the request and starts a new PHP process. This process loads the PHP file, runs the code from top to bottom, generates output (usually HTML), sends it back to the user's browser, and then stops.
Result
Each request is handled independently with no leftover data from previous requests.
Understanding that PHP starts fresh for every request helps explain why variables don't keep their values between page loads.
2
FoundationStateless nature of PHP processes
🤔
Concept: PHP processes do not keep memory or state between requests by default.
Because each PHP process ends after sending output, all variables, objects, and data in memory are lost. This means PHP scripts are stateless unless you use external storage like files, databases, or sessions.
Result
No automatic memory or data sharing between requests.
Knowing PHP is stateless by default clarifies why developers need sessions or databases to remember user info.
3
IntermediateHow PHP integrates with web servers
🤔Before reading on: do you think PHP runs inside the web server process or separately? Commit to your answer.
Concept: PHP can run as a separate process or module depending on the server setup.
PHP can run as a CGI process, FastCGI, or as an Apache module. In CGI/FastCGI, the server starts a new PHP process per request or reuses a pool. As a module, PHP runs inside the web server process but still resets state per request.
Result
Different setups affect performance but the per-request model stays consistent.
Understanding server integration explains performance differences and why PHP still resets state even inside server modules.
4
IntermediateRole of PHP opcode caching
🤔Before reading on: does opcode caching keep your variables between requests? Commit to your answer.
Concept: Opcode caching stores compiled PHP code to speed up execution but does not keep runtime data between requests.
Opcode caches like OPcache save the compiled version of PHP scripts in memory so PHP doesn't recompile them every time. However, each request still runs in a fresh process with fresh variables.
Result
Scripts run faster but still start with a clean state each request.
Knowing opcode caching only speeds up code loading prevents confusion about persistent variables.
5
AdvancedPersistent data via sessions and storage
🤔Before reading on: do you think PHP automatically remembers user data between requests? Commit to your answer.
Concept: PHP uses external mechanisms like sessions and databases to keep data across requests because processes are short-lived.
To remember user info, PHP uses sessions that store data on the server linked by a cookie. Databases or files also save data permanently. This is necessary because PHP processes forget everything after finishing.
Result
User data persists across page loads despite PHP's stateless process model.
Understanding external storage is essential to build interactive, stateful web apps with PHP.
6
ExpertLong-running PHP processes and workers
🤔Before reading on: can PHP processes run continuously to handle multiple requests? Commit to your answer.
Concept: Advanced PHP setups use long-running processes or workers to improve performance but must manage state carefully.
Tools like PHP-FPM keep PHP processes alive to handle many requests, reducing startup cost. However, developers must avoid relying on in-memory variables to persist between requests, as this can cause bugs or memory leaks.
Result
Better performance but requires careful coding to avoid state-related errors.
Knowing the difference between per-request and long-running PHP processes helps avoid subtle bugs in production.
Under the Hood
When a request arrives, the web server invokes the PHP interpreter as a new process or uses a persistent process pool. The PHP engine reads the script, compiles it into opcode, executes it, and sends output. After execution, the process cleans up memory and exits or waits for the next request if persistent. No variables or runtime data survive beyond this cycle unless saved externally.
Why designed this way?
PHP was designed for simplicity and security, isolating each request to prevent data leaks and side effects. Early web hosting environments favored this model for easy resource management and crash isolation. Alternatives like persistent processes existed but added complexity and risk, so PHP kept the per-request model as default.
┌───────────────┐
│ HTTP Request  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Web Server    │
│ (e.g. Apache) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ PHP Interpreter│
│ (new process) │
│ Compile & Run │
│ Send Output   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ HTTP Response │
Myth Busters - 4 Common Misconceptions
Quick: Does PHP keep your variables in memory between page loads? Commit to yes or no.
Common Belief:PHP remembers all variables and data automatically between requests.
Tap to reveal reality
Reality:PHP processes start fresh for each request, so variables do not persist unless saved externally.
Why it matters:Assuming variables persist causes bugs where data disappears unexpectedly between pages.
Quick: Does opcode caching keep your PHP variables alive between requests? Commit to yes or no.
Common Belief:Opcode caching means PHP remembers all data and variables between requests.
Tap to reveal reality
Reality:Opcode caching only saves compiled code, not runtime data or variables.
Why it matters:Confusing opcode caching with data persistence leads to wrong assumptions about state management.
Quick: Can PHP processes run continuously and handle multiple requests without restarting? Commit to yes or no.
Common Belief:Each PHP process handles only one request and then dies immediately, no exceptions.
Tap to reveal reality
Reality:With PHP-FPM or similar, processes can stay alive and handle many requests, but still reset state per request.
Why it matters:Not knowing this can cause confusion about performance tuning and memory leaks in production.
Quick: Does running PHP as an Apache module mean variables persist between requests? Commit to yes or no.
Common Belief:Running PHP inside the web server means variables stay in memory across requests.
Tap to reveal reality
Reality:Even as a module, PHP resets all variables each request to keep isolation.
Why it matters:Believing otherwise can cause security risks and unpredictable behavior.
Expert Zone
1
PHP's per-request model simplifies crash recovery because each request is isolated; a crash affects only that request.
2
Long-running PHP processes require explicit memory management to avoid leaks since the process does not restart automatically.
3
Session data is stored outside PHP processes, often in files or databases, to maintain user state across stateless requests.
When NOT to use
Avoid relying on PHP's per-request model for real-time or persistent connections like WebSockets; instead, use specialized servers or frameworks designed for long-lived connections such as ReactPHP or Swoole.
Production Patterns
In production, PHP-FPM is commonly used to keep pools of PHP processes alive for better performance, combined with opcode caching and external session storage to balance speed and statelessness.
Connections
HTTP Protocol
PHP's per-request model aligns with HTTP's stateless request-response nature.
Understanding HTTP's statelessness helps grasp why PHP resets state each request and needs external storage for persistence.
Operating System Process Model
PHP processes per request mirror OS process isolation and lifecycle management.
Knowing how OS processes start and end clarifies PHP's fresh environment per request and resource cleanup.
Functional Programming
PHP's stateless request model resembles pure functions that have no side effects or memory between calls.
Seeing PHP scripts as pure functions per request helps understand why side effects must be managed externally.
Common Pitfalls
#1Expecting variables to keep their values between page loads.
Wrong approach:
Correct approach:
Root cause:Misunderstanding that PHP variables reset every request and not using sessions or external storage.
#2Assuming opcode caching keeps runtime data alive.
Wrong approach:
Correct approach:
Root cause:Confusing compiled code caching with runtime data persistence.
#3Storing large data in global variables expecting persistence in PHP-FPM.
Wrong approach:
Correct approach:
Root cause:Not realizing PHP-FPM processes reset variables per request despite process persistence.
Key Takeaways
PHP runs each request in a new process or fresh environment, so no variables or data persist automatically between requests.
This per-request model keeps web applications simple, secure, and isolated but requires external storage for state.
Opcode caching speeds up PHP by saving compiled code but does not keep runtime data alive.
Advanced setups use persistent PHP processes for performance but still reset state per request to avoid bugs.
Understanding this model is essential to correctly manage user sessions, data persistence, and performance in PHP applications.

Practice

(1/5)
1. What happens to PHP variables after a web request finishes?
easy
A. They become global variables accessible by all users
B. They keep their values for the next request automatically
C. They are stored permanently in the server memory
D. They are reset and lost unless saved externally

Solution

  1. Step 1: Understand PHP request lifecycle

    PHP starts fresh for each request, so variables exist only during that request.
  2. Step 2: Identify variable persistence

    Variables reset after request ends unless saved in sessions or databases.
  3. Final Answer:

    They are reset and lost unless saved externally -> Option D
  4. Quick Check:

    PHP variables reset each request = D [OK]
Hint: Remember: PHP starts fresh every request, no variable memory [OK]
Common Mistakes:
  • Thinking variables persist automatically between requests
  • Confusing PHP with long-running server processes
  • Assuming global variables keep values across users
2. Which PHP code snippet correctly shows the start of a new request process?
easy
A.
B.
C.
D.

Solution

  1. Step 1: Analyze variable initialization

    In a new request, variables start fresh; $count = 0 sets it properly.
  2. Step 2: Check other options for persistence

    Options A, B, D try to increment without initialization or rely on static/session which need extra setup.
  3. Final Answer:

    <?php $count = 0; echo $count; ?> -> Option C
  4. Quick Check:

    New request means fresh variables = C [OK]
Hint: Fresh request means variables start from scratch [OK]
Common Mistakes:
  • Assuming static variables keep value across requests
  • Using session without starting it
  • Incrementing uninitialized variables
3. What will be the output of this PHP code when run twice in separate requests?
<?php
session_start();
if (!isset($_SESSION['visits'])) {
  $_SESSION['visits'] = 1;
} else {
  $_SESSION['visits']++;
}
echo $_SESSION['visits'];
?>
medium
A. 1 then 2
B. 1 then 1
C. 2 then 3
D. Error on second request

Solution

  1. Step 1: Understand session persistence

    Session data keeps values across requests, so visits count increases.
  2. Step 2: Trace two requests

    First request sets visits=1; second request increments to 2.
  3. Final Answer:

    1 then 2 -> Option A
  4. Quick Check:

    Session stores visits count = 1 then 2 [OK]
Hint: Sessions keep data between requests, variables do not [OK]
Common Mistakes:
  • Thinking variables persist without sessions
  • Forgetting to call session_start()
  • Expecting static variables to persist across requests
4. Identify the error in this PHP code snippet that tries to keep a counter across requests:
<?php
$count = 0;
$count++;
echo $count;
?>
medium
A. Variables reset each request, so counter never increases
B. Syntax error due to missing semicolon
C. Session not started, so counter is undefined
D. Static variable needed to keep count

Solution

  1. Step 1: Check variable behavior per request

    $count is set to 0 every time, so increment always starts fresh.
  2. Step 2: Identify persistence issue

    Without sessions or external storage, counter resets each request.
  3. Final Answer:

    Variables reset each request, so counter never increases -> Option A
  4. Quick Check:

    Variables reset each request = A [OK]
Hint: Variables reset each request; use sessions to persist [OK]
Common Mistakes:
  • Assuming static variables persist across requests
  • Confusing syntax errors with logic errors
  • Forgetting to start sessions for persistence
5. You want to count unique visitors to your PHP website. Which approach correctly uses PHP's process model per request to achieve this?
hard
A. Use a static variable in PHP script to count visitors
B. Store visitor count in a database and increment on each request
C. Increment a PHP variable without sessions or storage
D. Rely on PHP variables to keep count across requests

Solution

  1. Step 1: Understand PHP process model limits

    PHP variables reset each request, so they can't keep visitor count.
  2. Step 2: Identify persistent storage method

    Database stores data permanently and can be updated each request.
  3. Final Answer:

    Store visitor count in a database and increment on each request -> Option B
  4. Quick Check:

    Persistent storage needed for visitor count = A [OK]
Hint: Use database or sessions to save data beyond request [OK]
Common Mistakes:
  • Using static or normal variables expecting persistence
  • Ignoring need for external storage
  • Confusing sessions with static variables
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard