Deep understanding of PHP Bottom: Php life cycle

Source: Internet
Author: User
Tags 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:

PHP request)

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 starts the process, That is, occurs before any request arrives. is the start phase (Minit) of the entire SAPI life cycle (for example, the entire life cycle of Apache startup or the entire execution of a command-line program), which is done only once.   module at this stage, you can do some initialization work, such as registering constants, defining the classes used by the module, and so on. Typical module callback function minit method is as follows:

    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, this request The environment variables required to execute the script, such as creating an execution environment, including a symbol table that holds the contents of variable names and variable values during PHP run. and a symbol table for all current functions and information such as classes. For example, Rinit of the session module, if the session module is enabled in PHP.ini, The $_session variable is initialized when the module's rinit is called, and the relevant content is read into;  and PHP invokes all the module Rinit functions.

    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:
    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. }

The second link: Finally, all the requests have been processed and SAPI is ready to close, 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:

    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 initialization phase (modules init)
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


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

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 multithreaded mode is similar to a process in a multi-process, the difference is that the entire process of the life cycle will be parallel to the request to start-the closure of the link.

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

Related Article

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.