Home > Article > Backend Development > Detailed explanation of the PHP life cycle at the bottom of PHP
This article mainly shares with you the detailed explanation of the PHP life cycle at the bottom of PHP. I hope it can help you.
The two operating modes of PHP are WEB mode and CLI mode. No matter which mode, PHP works the same, running as a SAPI.
#1. When we type the php command in the terminal, it uses the CLI.
It is like a web server to support PHP to complete the request. After the request is completed, control is returned to the terminal.
2. When using Apache or another web server as the host, when a request comes, PHP will support the completion of the request. Generally:
## Multi-process (usually compiled as an apache module to handle
PHP requests)
Multi-threaded mode
2. The beginning of everything: SAPI interface Usually when we write PHP Web programs, we test the script through Web servers such as Apache or Nginx. Or Execute the PHP script through the php program on the command line. After the script is executed, the server responds and the browser displays the response information, or displays the content on the standard output after the command ends. We rarely care about where the PHP interpreter is. Although executing scripts through a web server and a command line program look very different, in fact their work is the same. Command line programs are similar to web programs, and command line parameters are passed to the execution The script is equivalent to requesting a PHP page through the URL. After the script is completed, the response result is returned, but the command line response result is displayed on the terminal. The beginning of the script execution is performed through the SAPI interface.1). Start apache:When a given SAPI starts, for example, in the response to /usr/local/apache/bin/apachectl start, PHP Start by initializing its kernel subsystem. Near the end of the startup routine, it loads each extension's code and calls its module initialization routine (MINIT). This allows each extension to initialize internal variables, allocate resources, register resource handlers, and register its own functions with ZE so that ZE knows what code to execute when a script calls one of these functions.
2) Request processing initialization: Next, PHP waits for the SAPI layer to request the page to be processed. For SAPIs like CGI or CLI, this will happen immediately and only once. For Apache, IIS or other mature web server SAPI, this will happen every time the remote user requests the page, so it will be repeated many times, possibly concurrently. Regardless of how the request is generated, PHP starts by asking ZE to set up the script's execution environment, and then calls each extension's request initialization (RINIT) function. RINIT gives extensions the opportunity to set specific environment variables, allocate resources upon request, or perform other tasks such as auditing. There is a typical example of the role of RINIT in session extension. If the session.auto_start option is enabled, RINIT will automatically trigger the session_start() function in user space and the preassembled $_SESSION variable.
3) Execute php code: Once the request is initialized, ZE begins to take over control, translates the PHP script into symbols, and finally forms the operation code and runs it step by step. If any opcode needs to call an extended function, ZE will bind the parameters to the function and temporarily relinquish control until the function completes.
4) End of script: After the script runs, PHP calls each extended request shutdown (RSHUTDOWN) function to perform final cleanup work (such as saving session variables to disk) . Next, ZE performs a cleanup process (garbage collection) - effectively unset()ing every variable used during the previous request.
5), sapi shutdown: Once completed, PHP continues to wait for other document requests from SAPI or a shutdown signal. For SAPI such as CGI and CLI, there is no "next request", so the SAPI immediately starts closing. During shutdown, PHP again iterates through each extension, calls its module shutdown (MSHUTDOWN) function, and eventually shuts down its own kernel subsystem.
The brief process is as follows:
1. PHP runs with the startup of Apache;
2. PHP runs through mod_php5 The .so module is connected to Apache (specifically SAPI, Server Application Programming Interface);
3. PHP has three modules in total: kernel, Zend engine, and extension layer;
4. PHP kernel is used to Processing requests, file streams, error handling and other related operations;
5. Zend engine (ZE) is used to convert source files into machine language and then run it on a virtual machine;
6. The extension layer is a set of Functions, libraries, and streams are used by PHP to perform specific operations. For example, we need the mysql extension to connect to the MySQL database;
7. When ZE executes the program, it may need to connect to several extensions. At this time, ZE will hand over control to the extension and return it after processing the specific task;
8. Finally, ZE returns the program running results to the PHP kernel, which then transmits the results to the SAPI layer and finally outputs them to the browser.
The first process: apache starts process, which occurs before any request arrives. It is the beginning phase (MINIT) of the entire SAPI life cycle (such as the entire life cycle after Apache is started or the entire execution process of the command line program). This phase is only performed once.. After starting Apache, the PHP interpreter also starts; PHP calls the MINIT method of each extension (module), thereby switching these extensions to an available state. Take a look at what extensions are opened in the php.ini file; MINIT means "module initialization". Each module defines a set of functions, class libraries, etc. to handle other requests. The module can perform some initialization work at this stage, such as registering constants, defining classes used by the module, etc. Typical module callback function MINIT method is as follows:
PHP_MINIT_FUNCTION(myphpextension) { /* Initialize functions, classes etc */ } { // 注册常量或者类等初始化操作 return SUCCESS; }
The second process occurs in the request phase,When a page request occurs. The initialization process will be performed before each request (RINIT request starts).
After the request arrives, SAPI layer will hand over control to the PHP layer, PHP initializationThis request Environment variables required to execute the script , for example Create an execution environment, including a symbol table that saves variable names and variable value contents during PHP running. As well as the symbol table of all current functions, classes and other information.For example, it is the RINIT of the Session module. If the Session module is enabled in php.ini, the $_SESSION variable will be initialized when the RINIT of the module is called, and Read the relevant content; Then PHP will call the RINIT function of all modules, which is "request initialization". At this stage, each module can also perform some related operations. The RINIT function of the module is similar to the MINIT function. The RINIT method can be regarded as a preparation process, which will automatically start between program executions.
PHP_RINIT_FUNCTION(myphpextension) { // 例如记录请求开始时间 // 随后在请求结束的时候记录结束时间.这样我们就能够记录下处理请求所花费的时间了 return SUCCESS; }
After the request is processed, Entering the end phase, generally when the script is executed to the end or by calling the exit() or die() function, PHP will enter the end phase. Corresponding to the start phase, the end phase is also divided into two stages, one after the request ends (RSHUWDOWN ), one at the end of the SAPI life cycle (MSHUTDOWN).
##First link:Ending phase after the request is processed: After the request is processed, it enters the ending phase, and PHP will start the cleanup process. It will call the RSHUTDOWN method of each module in sequence.
RSHUTDOWN is used to clear the symbol table generated when the program is running, that is, to call the unset function on each variable. The typical RSHUTDOWN method is as follows:
PHP_RSHUTDOWN_FUNCTION(myphpextension) { // 例如记录请求结束时间, 并把相应的信息写入到日至文件中. return SUCCESS; }
Second link: Finally, all requests have been processed and SAPI is ready to be closed , PHP calls the MSHUTDOWN method of each extension. This is the last chance for each module to release memory. (This isFor SAPI such as CGI and CLI, there is no "next request", so the SAPI immediately starts closing. )
The typical RSHUTDOWN method is as follows:PHP_MSHUTDOWN_FUNCTION(extension_name) { /* Free handlers and persistent memory etc */ return SUCCESS; }In this way, the entire PHP life cycle is over. It should be noted that the "starting step one" and "closing step two" will only be executed if there is no request from the server.
SAPI runs PHP through the following stages:
1. Module initialization phase (Module init) :
That is, calling each extension source code The methods in PHP_MINIT_FUNCTION initialize the module, apply for some variables required by the module, allocate memory, etc.
2. Request initialization phase (Request init) :
After receiving the client’s request, the method in each extended PHP_RINIT_FUNCTION is called to initialize the execution of the PHP script. environment.
3. Execute PHP script
4.Request Shutdown :
Called at this time Each extension's PHP_RSHUTDOWN_FUNCTION method cleans up the request site, and ZE begins reclaiming variables and memory.
5. Shut down the module (Module shutdown) :
When the Web server exits or the command line script is executed and exits, the PHP_MSHUTDOWN_FUNCTION method in the extension source code will be called
CLI/CGI mode PHP belongs to the single-process SAPI mode. This type of request is closed after processing the request once. That is to say, it will only go through the following links: Start - Request starts - Request closes - End The SAPI interface implementation completes its life cycle. As shown in the figure:
to Module to handle PHP requests. Apache generally adopts multi-process mode. After Apache is started, it will
fork multiple child processes. Each process has an independent memory space. Each child process will go through the start and end stages. However, the start stage of each process
The segment is only performed after the process forks out. Multiple requests may be processed during the entire process life cycle. Only if Apache is shut down or process
被结束之后才会进行关闭阶段,在这两个阶段之间会随着每个请求重复请求开始-请求关闭的环节。
如图所示:
多线程模式和多进程中的某个进程类似,不同的是在整个进程的生命周期内会并行的重复着 请求开始-请求关闭的环节.
在这种模式下,只有一个服务器进程在运行着,但会同时运行很多线程,这样可以减少一些资源开销,向Module init和Module shutdown就只需要运行一遍就行了,一些全局变量也只需要初始化一次,因为线程独具的特质,使得各个请求之间方便的共享一些数据成为可能。
多线程工作方式如下图
在linux下使用#http –l 命令可以查看当前使用的工作模式。也可以使用#apachectl -l命令。
看到的prefork.c,说明使用的prefork工作模式。
prefork 进程池模型,用在 UNIX 和类似的系统上比较多,主要是由于写起来方便,也容易移植,还不容易出问题。要知道,如果采用线程模型的话,用户线程、内核线程和混合型线程有不同的特性,移植起来就麻烦。prefork 模型,即预先 fork() 出来一些子进程缓冲一下,用一个锁来控制同步,连接到来了就放行一个子进程,让它去处理。
prefork MPM 使用多个子进程,每个子进程只有一个线程。每个进程在某个确定的时间只能维持一个连接。在大多数平台上,Prefork MPM在效率上要比Worker MPM要高,但是内存使用大得多。prefork的无线程设计在某些情况下将比worker更有优势:他能够使用那些没有处理好线程安全的第三方模块,并 且对于那些线程调试困难的平台而言,他也更容易调试一些。
The above is the detailed content of Detailed explanation of the PHP life cycle at the bottom of PHP. For more information, please follow other related articles on the PHP Chinese website!