Deep understanding of PHP Bottom: PHP life cycle [GO]

Source: Internet
Author: User
Tags php script sapi zend

1, PHP mode of operation:

PHP Two mode of operation is Web mode, CLI mode. Regardless of the mode, PHP works the same way, running as a SAPI.

1. When we typed the PHP command at the terminal, it was using the CLI.

It is like a Web server to support PHP to complete this request, the request is completed and then re-control to the terminal.

2. When using Apache or a Web server as the host, PHP will support this request when a request arrives. There are generally:

Multi-process (usually compiled as Apache module to handle PHP requests)

Multithreaded mode

2, the beginning of everything: SAPI interface

Usually we write PHP Web programs through the Apache or Nginx Web server to test the script. Or you can execute PHP scripts from the command line through a PHP program. After executing the script, the server answers, the browser displays the response information, or displays the content in the standard output after the command finishes. We seldom care where the PHP interpreter is. Although executing scripts through the Web server and the command-line program looks very different. In fact, their work is the same. A command-line program is similar to a Web program, where command-line arguments are passed to the script to be executed, which is equivalent to requesting a PHP page via a URL. The response results are returned when the script stamp is complete, except that the result of the command line response is displayed on the terminal. The start of the script execution is done 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 starts by initializing its kernel subsystem. At the end of the approach to the startup routine, it loads the code for each extension and calls its module initialization routines (MINIT). This allows each extension to initialize internal variables, allocate resources, register resource handlers, and register its own functions with ze so that the script calls this function ze know what code to execute.

2), request processing initialization : Next, PHP waits for the SAPI layer to request the page to be processed. For SAPI such as CGI or CLI, this will happen immediately and only once. For Apache, IIS, or other mature Web server SAPI, each time a remote user requests a page, it is repeated many times and may be concurrent. Regardless of how the request was generated, PHP begins with the runtime environment that requires Ze to build the script, and then calls each extended request initialization (Rinit) function. Rinit gives the extension the opportunity to set specific environment variables, allocate resources on request, or perform other tasks, such as auditing. There is a typical example of a Rinit action in the session extension, and if the Session.auto_start option is enabled, Rinit will automatically trigger the Session_Start () function of the user space and the pre-assembled $_session variable.

3), execute PHP code : Once the request is initialized, Ze begins to take control, translates the PHP script into symbols, and eventually forms the opcode and runs gradually. If any of the opcode needs to call the extended function, ze will bind the parameter to the function and temporarily hand over the control until the function is run.

4), script end: After the script runs, PHP calls each extended request shutdown (Rshutdown) function to perform the final cleanup work (such as saving the session variable to disk). Next, Ze performs the cleanup process (garbage collection)-effectively executing unset () for each variable used during the previous request.

5), sapi off : Once completed, PHP continues to wait for SAPI's other documentation requests or to turn off the signal. for SAPI such as CGI and CLI, there is no "next request", so SAPI immediately begins to shut down . During shutdown, PHP iterates through each extension again, invokes its module shutdown (mshutdown) function, and eventually shuts down its own kernel subsystem.

The brief process is as follows:

1. PHP is running as Apache starts;
2. PHP is connected to Apache via the Mod_php5.so module (specifically, SAPI, the server Application programming interface);
3. PHP has a total of three modules: the kernel, the Zend engine, and the expansion layer;
4. The PHP kernel is used to handle requests, file streams, error handling and other related operations;
5. The Zend Engine (ZE) is used to convert the source file into a machine language and then run it on the virtual machine;
6. The extension layer is a set of functions, class libraries, and streams that PHP uses to perform certain operations. For example, we need MySQL extension to connect to MySQL database;
7. When Ze executes the program, it may be necessary to connect a number of extensions, then Ze will control to the extension, and so on after the specific tasks are processed and then returned;
8. Finally, ZE returns the result of the program run to the PHP kernel, which then transmits the results to the SAPI layer, which is eventually output to the browser.

3. There are two processes at the beginning and end stages of PHP:

the first procedure: Apache initiates a process that occurs before any request arrives . Is the beginning (minit) of the entire SAPI life cycle (for example, the entire lifecycle of an Apache or the entire execution of a command-line program), which is performed only once: After starting Apache, the PHP interpreter also starts, and PHP invokes the Minit method of each extension (module), which allows the extensions to switch to the available state. See what extensions are open in the php.ini file, and Minit means "module initialization." Each module defines a set of functions, class libraries, and so on to handle other requests. Modules can perform some initialization work at this stage, such as registering constants, defining classes used by modules, and so on. A typical module callback function Minit method is as follows:

[CPP]View PlainCopyprint?
    1. Php_minit_function (myphpextension) {/ * Initialize functions, classes etc *}
    2. {
    3. //Register constants or initialize operations such as classes
    4. return SUCCESS;
    5. }

The second process occurs at the request stage , when a page request occurs. The initialization process is performed before each request (the Rinit request begins).

After the request arrives, the SAPI layer gives control to the PHP layer, and PHP initializes the environment variables required for this request to execute the script, such as creating an execution environment, including a symbol table that holds the variable name and variable value contents during PHP run.  and a symbol table for all current functions and information such as classes. For example, the Rinit of the session module, if the session module is enabled in PHP.ini, the $_session variable is initialized when the rinit of the module is called, and the relevant content is read into; PHP then invokes all module Rinit functions, called "Request initialization." At this stage the modules can also perform some related operations, the module's Rinit function and the Minit function are similar, the Rinit method can be regarded as a preparation process, will automatically start between program execution.

[CPP]View PlainCopyprint?
    1. Php_rinit_function (myphpextension)
    2. {
    3. //For example, record request start time
    4. The end time is then recorded at the end of the request. So we can record the time it takes to process the request .
    5. return SUCCESS;
    6. }
The end stage is divided into two sections:after the request has been processed, it enters the end stage, and the general script executes to the end or by calling exit () or the Die () function, and PHP will go to the end stage. Corresponding to the start phase, the end stage is divided into two links, one after the request is over (Rshuwdown), One at the end of the SAPI life cycle (Mshutdown).
 the First link: after the request processing end phase : After processing the request to enter the end phase, PHP will start the cleanup program. It invokes the Rshutdown method of each module sequentially. Rshutdown is used to clear the symbol table generated by the program runtime, which is called the unset function for each variable. The typical Rshutdown method is as follows:
[CPP]View PlainCopyprint?
    1. Php_rshutdown_function (myphpextension)
    2. {
    3. //For example, record the request end time and write the corresponding information to the date to the file.
    4. return SUCCESS;
    5. }

Second Link: Finally, all the requests have been processed, SAPI is ready to shut down, and PHP calls each extended Mshutdown method, which is the last chance for each module to release memory. ( This is for SAPI such as CGI and CLI, there is no "next request", so SAPI immediately begins to shut down . )

The typical Rshutdown method is as follows:

[Plain]View PlainCopyprint?
    1. Php_mshutdown_function (extension_name) {
    2. /* Free handlers and persistent memory etc */
    3. return SUCCESS;
    4. }

In this way, the entire PHP life cycle is over. It is important to note that the "Start first step" and "close second step" are performed only if the server does not have a request.

SAPI run PHP through the following stages:
1. Module init phase :
That is to call each extension of the source in the Php_minit_function method initialization module, to do some of the modules required variables, memory allocation and so on.
2. request initialization phase (ask Init) :
The execution environment of the PHP script is initialized by invoking the method in each extended php_rinit_function after receiving the request from the client.
3. Execute PHP script
4. End of request (Shutdown) :
At this time each extended Php_rshutdown_function method is called to clean the request site, and Ze begins to reclaim variables and memory.
5. Close Module (modules shutdown) :
The Web server exits or the command-line script finishes executing exit calls the Php_mshutdown_function method in the extended source code

4. Single Process SAPI life cycle

cli/cgi mode PHP is a single-process SAPI mode. This type of request is closed after processing a request. That is, it only passes through the following links: Start-Request Start-Request shutdown-end the SAPI interface implementation completes its life cycle. :

5. Multi-process SAPI life cycle

PHP is usually compiled as a module of Apache to handle PHP requests. Apache typically uses multi-process mode, and Apache starts

Fork out many sub-processes, each process of memory space Independent, each sub-process will go through the start and end links, but the beginning of each process

Segments occur only after the process has been forked, and multiple requests may be processed throughout the lifetime of the process. Only in Apache shutdown or process

The shutdown phase occurs after the end of the session, and between the two phases begins with a repeat request for each request-the link for the request to close.

6, Multi-threaded SAPI life cycle

The multithreading pattern is similar to a process in a multi-process, and the difference is that the request initiation-request closure is repeated in parallel throughout the life cycle of the process.

In this mode, only one server process is running, but it will run many threads at the same time, which can reduce some resource overhead, just need to run it once for Module Init and module shutdown, and some global variables only need to be initialized once, because the thread has unique characteristics, Makes it possible to share some data conveniently between requests.

Multi-threaded working methods such as

7, Apache general use multi-process mode prefork

Use the #http–l command under Linux to see the current mode of work being used. You can also use the #apachectl-l command.
See the PREFORK.C that illustrates the use of the Prefork working mode.

Prefork process pool model, used in UNIX and similar systems more, mainly because it is easy to write, but also easy to transplant, is not prone to problems. You know, if you adopt a threading model, user threads, kernel threads, and hybrid threads have different features that can be cumbersome to transplant. Prefork model, that is, pre-fork () out some of the sub-process buffer, with a lock to control synchronization, the connection arrives to release a child process, let it deal with.

    Prefork MPM uses multiple child processes, with only one thread per child process. Each process can only maintain one connection at a certain time. On most platforms, the Prefork MPM is more efficient than the worker mpm, but the memory usage is much larger. Prefork's wireless path design in some cases will be more advantageous than the worker: he is able to use third-party modules that do not handle thread safety, and he is more likely to debug some of the platforms that are difficult to debug.

Deep understanding of PHP Bottom: PHP life cycle [GO]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.