search
HomeBackend DevelopmentPHP TutorialAn article explaining the principle and use of PHP opcache in detail

This article brings you relevant knowledge about PHP opcache. It mainly talks about how to understand the OPCache function and how to use it. Interested friends can take a look at it together. I hope Helpful to everyone.

An article explaining the principle and use of PHP opcache in detail

In PHP projects, especially in scenarios with high concurrency and large traffic, how to improve the response time of PHP is a very important task.
Opcache is an indispensable component for optimizing PHP performance, especially in projects that apply the PHP framework.

1. Overview

Before understanding the OPCache function, we must first understand the working mechanism of PHP-FPM Nginx and the mechanism of PHP script interpretation and execution.

1.1 The working mechanism of PHP-FPM Nginx

The request goes from the web browser to Nginx, and then to PHP processing. There are a total of five steps:
First Step: Start the service

  • #Start PHP-FPM. PHP-FPM supports two communication modes: TCP socket and Unix socket;

  • PHP-FPM will start two types of processes: Master process and Worker process. The former is responsible for monitoring ports and allocation Tasks and management Worker processes; the latter is PHP's cgi program, which is responsible for interpreting, compiling and executing PHP scripts.

  • Start Nginx. First, the ngx_http_fastcgi_module module will be loaded to initialize the FastCGI execution environment and implement the FastCGI protocol request proxy

  • Note here: the fastcgi worker process (cgi process) is managed by PHP-FPM. Not Nginx. Nginx is just a proxy

Second step: Request => Nginx

  • Nginx receives the request and configures it based on location , choose a suitable handler

  • Here is the handler for proxy PHP

##The third step: Nginx => PHP-FPM

  • Nginx translates the request into a fastcgi request

  • Sends it to the master process of PHP-FPM through TCP socket/Unix Socket

Step 4: PHP-FPM Master => Worker

  • PHP-FPM master process receives the request

  • Assign the Worker process to execute the PHP script. If there is no idle Worker, a 502 error will be returned.

  • The Worker (php-cgi) process executes the PHP script. If it times out , returns 504 error

  • Processing ends, returns result

##Step 5: PHP-FPM Worker => Master => ; Nginx

    PHP-FPM Worker process returns the processing result, closes the connection, and waits for the next request
  • PHP-FPM Master The process returns the processing results through Socket
  • Nginx Handler sends each response buffer to the first filter in sequence → the second → and so on → the final response is sent to the client
  • 1.2 The mechanism of PHP script interpretation and execution

After understanding the overall processing flow of PHP Nginx, let’s take a look at the specific execution flow of PHP scripts. First, let’s look at an example:

<p><?php    <br/>    if (!empty($_POST)) {<br>        echo "Response Body POST: ", json_encode($_POST), "\n";<br>    }<br>    if (!empty($_GET)) {    <br>        echo "Response Body GET: ", json_encode($_GET), "\n";<br>    }<br></p>

Let’s analyze the execution process:

1.php initializes the execution link, starts the Zend engine, and loads the registered extension module2. After initialization, read the script file, Zend The engine performs lexical analysis (lex) and syntax analysis (bison) on the script file to generate a syntax tree
3.Zend engine compiles the syntax tree and generates opcode,
4.Zend engine executes opcode and returns the execution result

In PHP cli mode, each time a PHP script is executed, the four steps will be executed in sequence;

In PHP-FPM mode, step 1) is executed once when PHP-FPM starts, and will not be executed in subsequent requests. Execute again; steps 2)~4) must be executed for each request;

In fact, the syntax tree and opcode generated by steps 2) and 3), the same PHP script will have the same result every time it is run. In PHP -In FPM mode, each request must be processed again, which is a huge waste of system resources. So is there any way to optimize it?

Of course, such as:

##OPCache: formerly known as Zend Optimizer, it is an open source component of Zend Server; official product, highly recommended
  • APC: Alternative PHP Cache is an open and free PHP opcode caching component, used to cache and optimize PHP intermediate code; it is no longer updated and is not recommended
  • APCu: It is a branch of APC, shares memory, caches user data, cannot cache opcode, and can be used with Opcache
  • eAccelerate: also not updated, not recommended
  • xCache: It is no longer recommended to use
  • 2. Introduction to OPCache

OPCache is officially produced by Zend and is open The free opcode cache extension also has code optimization functions, eliminating the overhead of loading and parsing PHP scripts each time. The OPcache extension has been bundled in PHP 5.5.0 and subsequent versions. Cache two types of content:


OPCode
  • Interned String, such as comments, variable names, etc.
  • 3. OPCache principle

The main mechanism of OPCache caching is to put compiled operation codes into shared memory and provide access to other processes. This involves the memory sharing mechanism. In addition, all memory resource operations have locking issues. We will explain them one by one.

3.1 Shared memory

UNIX/Linux systems provide many ways to share memory between processes:

1.System-V shm API: System V shared memory
sysv shm is persistent unless explicitly stated by a process deleted, otherwise it will always exist in the memory until the system is shut down;
2.mmap API:

  • The memory mapped by mmap is not persistent. If the process is shut down, the mapping It will become invalid immediately, unless it has been mapped to a file in advance

  • The memory mapping mechanism mmap is a POSIX standard system call, and there are two types: anonymous mapping and file mapping

  • One of the advantages of mmap is that it maps files to the address space of the process

  • avoids the copying process of data from the user buffer to the kernel page cache buffer;

  • Of course, another advantage is that frequent read/write system calls are not required

3.POSIX API:
System V’s shared memory is Outdated, POSIX shared memory provides an API that is simpler to use and more rationally designed.

4.Unix socket API

OPCache uses the first three shared memory mechanisms, depending on the configuration or default mmap Memory sharing mode. According to the scenario of PHP bytecode caching, OPCache's memory management design is very simple, with fast reading and writing, no memory release, and expired data is set to Wasted.
When the Wasted memory is greater than the set value, the OPCache mechanism is automatically restarted, the cache is cleared and regenerated.

3.2 Mutex lock

Any operation of memory resources involves the lock mechanism.
Shared memory: Only one process is allowed to perform write operations in a unit time, and multiple processes are allowed to perform read operations; while writing operations are performed, read operations are not blocked, so that there is rarely a lock-up situation.
This leads to another problem: new code, large traffic scenarios, processes queue up to perform cache opcode operations; repeated writing leads to waste of resources.

4. OPCache cache interpretation

OPCache is the official Opcode cache solution. After PHP5.5 version, it has been packaged into PHP source code and released together.
It caches the bytecode and data generated by PHP compilation into shared memory. At each request, the compiled opcode is directly read from the cache and executed.
Improve the running efficiency of PHP by saving the script compilation process. If you are using the APC extension to do the same job, it is now highly recommended to use OPCache instead, especially in PHP7.

4.1 OPCode

Cache Opcache will cache OPCode and the following content:

  • Functions involved in PHP scripts

  • Class defined in PHP script

  • PHP script file path

  • PHP script OPArray

  • PHP script’s own structure/content

4.2 Interned String

Caching First we need to understand, what is Interned String?
In PHP5.4, the Interned String mechanism was introduced to optimize PHP's storage and processing of strings. Especially when dealing with large blocks of strings, such as PHP doces, Interned String can optimize memory. The contents of the Interned String cache include: variable names, class names, method names, strings, comments, etc.

In PHP-FPM mode, Interned String cache characters are limited to within the Worker process. If cached in OPCache, the Interned String cached string can be used between Worker processes to save memory.

We need to pay attention to one thing. In PHP development, there are usually large comments, which will also be cached in OPCache. You can turn off the caching of comments through the configuration of php.ini.
However, in frameworks such as Zend Framework, comments will be referenced, so whether to turn off the cache of comments needs to be treated differently.

5. OPCache update strategy

is a cache, which has expiration and update strategies. The update strategy of OPCache is very simple. The expired data is set to Wasted. When the set value is reached, the cache is cleared and the cache is rebuilt.
Note here: In high-traffic scenarios, rebuilding the cache is a very resource-consuming task. OPCache does not prevent other processes from reading when creating the cache. This results in a large number of processes repeatedly creating new caches. Therefore, do not set the OPCache expiration time

Every time new code is released, the cache will be repeatedly created. How to avoid it?

  • Don’t release code during peak periods, this is a rule that must be followed under any circumstances

  • Code warm-up, such as using script batch debugging PHP accesses the URL, or uses the API exposed by OPCache such as opcache_compile_file() for compilation and caching

6. OPCache configuration

6.1 Memory configuration

  • opcache.preferred_memory_model="mmap" OPcache's preferred memory module. If left blank, OPcache will select the applicable module. Normally, automatic selection will suffice. Optional values ​​include: mmap, shm, posix and win32.

  • opcache.memory_consumption=64 OPcache shared memory size in megabytes, default 64M

  • opcache.interned_strings_buffer=4 Use Memory size to store temporary strings, in megabytes, default 4M

  • opcache.max_wasted_percentage=5 The upper limit of wasted memory, in percentage. If this limit is reached, OPcache will generate a restart event. Default 5

6.2 Number and size of files allowed to be cached

  • opcache.max_accelerated_files=2000 The upper limit of the number of script files that can be stored in the OPcache hash table. The real value is the first prime number found in the prime number set {223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987} that is greater than or equal to the set value. The minimum value range of the setting value is 200, the maximum value is 100000 before PHP 5.5.6, and 1000000 after PHP 5.5.6. Default value 2000

  • opcache.max_file_size=0 The upper limit of cached file size in bytes. Set to 0 to cache all files. Default value 0

6.3 Comment related cache

  • opcache.load_commentsboolean If disabled, these will not be loaded even if the file contains comments Annotation content. This option can be used together with opcache.save_comments to load comment content on demand.

  • opcache.fast_shutdown boolean If enabled, fast stop resume events will be used. The so-called quick stop resumption event refers to the memory management module that relies on the Zend engine to release the memory of all requested variables at once, rather than releasing each allocated memory block in sequence.

6.4 Second-level cache configuration

  • opcache.file_cache Configure the second-level cache directory and enable the second-level cache. Enabling second-level cache can improve performance when the SHM memory is full, the server is restarted, or the SHM is reset. The default value is the empty string "", which disables file-based caching.

  • opcache.file_cache_onlyboolean Enables or disables opcode caching in shared memory.

  • opcache.file_cache_consistency_checksboolean Whether to verify the checksum of the file when loading the script from the file cache.

  • opcache.file_cache_fallbackboolean On Windows platforms, when a process cannot attach to shared memory, file-based caching is used, that is: opcache.file_cache_only=1. File caching needs to be enabled explicitly.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of An article explaining the principle and use of PHP opcache in detail. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools