Understanding PHP OPCache: Architecture, Mechanisms, and Configuration
This article explains how PHP‑FPM and Nginx handle requests, details the PHP script execution process, introduces OPCache and its shared‑memory design, describes its caching of opcodes and interned strings, and provides practical configuration and update‑strategy recommendations for high‑traffic PHP applications.
1. Overview
Improving PHP response time in high‑concurrency scenarios is crucial, and OPCache is an essential component for performance optimization, especially in framework‑based projects.
1.1 PHP‑FPM + Nginx Working Mechanism
Requests flow through five steps:
Start Services : PHP‑FPM (master and worker processes) and Nginx (loading ngx_http_fastcgi_module ) are launched.
Request → Nginx : Nginx receives the request and selects a FastCGI handler based on its location configuration.
Nginx → PHP‑FPM : Nginx translates the request to a FastCGI request and sends it via TCP or Unix socket to the PHP‑FPM master process.
PHP‑FPM Master → Worker : The master assigns a free worker to execute the PHP script; if none are available, a 502 error is returned, and a timeout results in a 504 error.
PHP‑FPM Worker → Master → Nginx : The worker returns the result, the master forwards it to Nginx, and Nginx streams the response to the client.
1.2 PHP Script Execution Mechanism
The execution consists of four stages:
Initialize the Zend engine and load extensions.
Lexical and syntax analysis to generate an abstract syntax tree.
Compile the syntax tree into opcodes.
Execute the opcodes and return the result.
In CLI mode these steps run for every script; in PHP‑FPM mode steps 2‑4 run on each request, which can be wasteful.
Example script:
<?php
if (!empty($_POST)) {
echo "Response Body POST: ", json_encode($_POST), "\n";
}
if (!empty($_GET)) {
echo "Response Body GET: ", json_encode($_GET), "\n";
}To avoid repeated parsing and compilation, opcode caches such as OPCache are used.
2. OPCache Introduction
OPCache, the official Zend opcode cache, is bundled with PHP 5.5+ and caches compiled bytecode and interned strings, eliminating the need to re‑parse scripts on each request.
3. OPCache Principles
OPCache stores compiled opcodes in shared memory, allowing all worker processes to read them without re‑compilation. It uses shared‑memory mechanisms (System‑V, mmap, POSIX) and employs simple memory‑management policies: fast read/write, no release, and automatic restart when wasted memory exceeds a threshold.
3.1 Shared Memory
Supported mechanisms include System‑V shm, mmap (default), and POSIX shm. OPCache selects the appropriate method based on configuration.
3.2 Mutex Locks
Write operations acquire an exclusive lock, while reads can proceed concurrently, minimizing lock contention but still requiring careful handling under high load.
4. OPCache Cache Details
OPCache caches:
Opcodes
Function definitions
Class definitions
File paths
OPArray structures
Script content
It also caches interned strings (variable names, class names, method names, literals, comments). Comments can be excluded via opcache.load_comments if desired.
5. OPCache Update Strategy
When cached data becomes “wasted” beyond the configured percentage, OPCache automatically restarts and rebuilds the cache. In high‑traffic environments, avoid setting a short expiration time; instead, pre‑warm the cache using opcache_compile_file() or by accessing URLs after deployment.
6. OPCache Configuration
6.1 Memory Settings
opcache.preferred_memory_model="mmap" – preferred shared‑memory backend.
opcache.memory_consumption=64 – shared memory size in MB (default 64 MB).
opcache.interned_strings_buffer=4 – interned string buffer size in MB.
opcache.max_wasted_percentage=5 – trigger restart when wasted memory exceeds 5 %.
6.2 File Limits
opcache.max_accelerated_files=2000 – maximum number of cached scripts.
opcache.max_file_size=0 – no size limit (0 means cache all files).
6.3 Comment Caching
opcache.load_comments (boolean) – enable/disable loading of comments.
opcache.fast_shutdown (boolean) – use fast shutdown to free request memory in one step.
6.4 Secondary Cache
opcache.file_cache="" – path to file‑based secondary cache (empty disables it).
opcache.file_cache_only (boolean) – use only file cache, disabling shared‑memory cache.
opcache.file_cache_consistency_checks (boolean) – verify file checksums when loading from the file cache.
opcache.file_cache_fallback (boolean) – fallback to file cache on Windows when shared memory cannot be attached.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.