How PHP executes/executes the process

Source: Internet
Author: User
Tags app service php language sapi zend

Http://www.cnblogs.com/hongfei/archive/2012/06/12/2547119.html

More in-depth learning and understanding can be viewed below:

Wind and Rain blog http://www.laruence.com/2008/08/12/180.html

Baidu Research Center's blog http://stblog.baidu-tech.com/?p=763

Wang Xingbin's Blog http://blog.csdn.net/wanghao72214/article/details/3916825

Brief introduction
Let's take a look at the following procedure:

    • We have never manually opened the relevant process of PHP, it is running with Apache boot;
    • PHP is connected to Apache via the Mod_php5.so module (specifically, SAPI, the Server Application programming interface );
    • PHP has a total of three modules: the kernel, the Zend engine, and the expansion layer ;
    • The PHP kernel is used to handle requests, file streams, error handling and other related operations;
    • The Zend Engine (ZE) is used to convert the source file into a machine language and then run it on the virtual machine;
    • An 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;
    • When Ze executes a program, it may be necessary to connect a number of extensions, then Ze will control to the extension, and so on after the completion of a specific task and then return;
    • Finally, ZE returns the results of the program to the PHP kernel, which then transmits the results to the SAPI layer, which is eventually output to the browser.

In-depth discussion
Wait, it's not that simple. The above process is just a brief version, let's dig deeper and see what else is happening behind the scenes.

    • After Apache starts, the PHP interpreter program also starts;
    • PHP Start-up process has two steps;
    • The first step is to initialize some environment variables, which will take effect throughout the SAPI life cycle;
    • The second step is to generate some variable settings for the current request only.

PHP Start the first step
Not sure what the first second step is? Don't worry, we'll discuss it in detail next. Let's take a look at the first step, but also the most important step. Keep in mind that the first step of the operation occurs before any requests arrive.

    • After starting Apache, the PHP interpreter also starts;
    • PHP invokes the Minit method of each extension, which enables these extensions to switch to the available state. See what extensions are open in the php.ini file;
    • Minit means "module initialization". Each module defines a set of functions, class libraries, and so on to handle other requests.

A typical Minit method is as follows:
Php_minit_function (extension_name) {
/* Initialize functions, classes etc * *
}
PHP starts the second step

    • When a page request occurs, the SAPI layer takes control over to the PHP layer. PHP then sets the environment variables that are required to respond to this request. It also creates a variable table that holds the variable names and values that are generated during execution.
    • PHP calls the Rinit method of each module, which is "request initialization". A classic example is the Rinit of the session module, if the session module is enabled in PHP.ini, the $_session variable is initialized when the module is called Rinit, and the relevant content is read into;
    • The Rinit method can be thought of as a preparation process that starts automatically between program execution.

A typical Rinit method is as follows:
Php_rinit_function (extension_name) {
/* Initialize Session variables, pre-populate variables, redefine global variables etc * *
}
PHP Close First Step
Like PHP startup, PHP is closed in two steps:

    • Once the page has been executed (either at the end of the file or with the exit or Die function aborted), PHP starts 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.

A typical Rshutdown method is as follows:
Php_rshutdown_function (extension_name) {
/* Do memory management, unset all variables used in the last PHP call etc */
}
PHP Close Second Step
Finally, all the requests have been processed and SAPI is ready to close, and PHP begins the second step:

    • PHP calls each extended Mshutdown method, which is the last opportunity for each module to release memory.

A typical Rshutdown method is as follows:
Php_mshutdown_function (extension_name) {
/* Free handlers and persistent memory etc */
}
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.

The following is illustrated with some illustrations!

How PHP works at the bottom

Figure 1 PHP structure

As you can see from the diagram, PHP is a 4-tier system from bottom to top.

①zend engine

Zend Whole with pure C implementation, is the core part of PHP, it will be PHP code translation (lexical, grammatical parsing, such as a series of compilation process) for the execution of opcode processing and implementation of the corresponding processing methods, the implementation of basic data structures (such as Hashtable, OO), memory allocation and management, The corresponding API method is provided for external invocation, which is the core of all, and all peripheral functions are implemented around Zend.

②extensions

Around the Zend Engine, extensions provides a variety of basic services through a component-based approach, our common set of built-in functions (such as the array series), standard libraries, etc. are implemented through extension, and users can implement their own extension as needed to achieve functional expansion , performance optimization and other purposes (such as the PHP middle layer is in use, Rich text parsing is the typical application of extension).

③sapi

SAPI full name is the server application programming Interface, which is the service-side application programming interface,SAPI through a series of hook functions, so that PHP can interact with the peripheral data , This is a very elegant and successful PHP design, through SAPI successfully decoupled PHP itself and the upper application decoupling , PHP can no longer consider how to be compatible with different applications, and the application itself can be used for their own characteristics to achieve different processing methods. Later in the SAPI section, we will introduce

④ Upper Application

This is our usual PHP program, through different SAPI way to get a variety of application patterns, such as through the webserver implementation of Web applications, command line under the script to run and so on.

Structure thought:

Engine (Zend) + component (EXT) mode reduces internal coupling

Middle tier (SAPI) isolated from Web server and PHP

**************************************************************************

If PHP is a car, then

The frame of the car is PHP itself.

Zend is the engine of the car (engine)

The various components under EXT are the wheels of the car.

SAPI can be seen as a road, and cars can run on different types of highways.

And once the PHP program is executed is the car running on the road.

So we need: engine with excellent performance + right wheels + right runway

the relationship between Apache and PHP

Apache's parsing of PHP is done through a number of module PHP module.

The eventual integration of PHP into the Apache system also requires some necessary settings for Apache. Here, we take PHP mod_php5 SAPI run mode as an example to explain, as for the concept of SAPI later we will explain in detail.

Assuming that the version we installed is Apache2 and PHP5, then you need to edit the Apache master configuration file http.conf, which includes the following lines:

Under Unix/linux Environment:

LoadModule Php5_module modules/mod_php5.so

AddType application/x-httpd-php. php

Note: Where modules/mod_php5.so is the installation location of the mod_php5.so file under the X system environment.

In the Windows environment:

LoadModule Php5_module D:/php/php5apache2.dll

AddType application/x-httpd-php. php

Note: Where D:/php/php5apache2.dll is the installation location of the Php5apache2.dll file in a Windows environment.

These two configurations are to tell Apache Server, in the future to receive the URL user request, usually in PHP as a suffix, you need to call the Php5_module module (mod_php5.so/php5apache2.dll) to handle.

The life cycle of Apache

Apach process of request processing

Apache Request processing Loop detailed
What has been done in the 11 phases of the Apache request processing cycle?

1. Post-read-request Stage

In the normal request processing process, this is the first stage in which a module can insert a hook. This phase can be exploited for modules that want to enter processing requests very early.

2. URI translation phase
Apache's primary work at this stage is to map the requested URL to the local file system. The module can insert hooks at this stage to perform its own mapping logic. Mod_alias is using this phase to work.

3. Header parsing Stage
The main work of Apache at this stage: Check the header of the request. This hook is rarely used because the module can perform the task of inspecting the request header at any point in the request processing process. Mod_setenvif is using this phase to work.

4. Access Control phase
The main work of Apache at this stage is to check whether the requested resource is allowed to be accessed based on the configuration file. The standard logic of Apache implements the Allow and deny directives. Mod_authz_host is using this phase to work.

5. Authentication Stage
Apache's main work at this stage is to authenticate the user according to the policy set by the profile and set the user name area. The module can insert hooks at this stage to implement an authentication method .

6. Authorization Stage
The main work of Apache at this stage is to check whether authenticated users are allowed to perform the requested action based on the profile. The module can insert hooks at this stage to implement a user Rights Management approach.

7. MIME Type Checking Stage
The main work of Apache at this stage is to determine which content handler will be used, based on the rules of the MIME type of the requested resource. The standard modules mod_negotiation and mod_mime implement this hook.

8. Fixup stage
This is a generic phase that allows the module to run any necessary process before the content generator . Similar to Post_read_request, this is a hook that captures any information and is the most commonly used hook.

9. Response Stage
The main work of Apache at this stage is to generate the content returned to the client, which is responsible for sending an appropriate reply to the client. This phase is a core part of the entire processing process.

10. Logging Stage
Apache's primary work at this stage is to log transactions after a reply has been sent to the client. The module may modify or replace the standard log records of Apache.

11. Cleanup Stage
Apache's main work at this stage is to clean up the environment left behind by the request transaction, such as file, directory processing, or socket closure , which is the last phase of Apache request processing.

Lamp Architecture:

From bottom to top four layers:

①liunx belongs to the bottom of the operating system

②apache server, belonging to secondary server, communication between Linux and PHP

③php: Belongs to the server-side programming language, via Php_module module and Apache Association

④mysql and other Web services: belong to app service, via PHP's Extensions plug-in module and MySQL Association

Android system architecture diagram

Lamp and Android architecture diagram comparison, looks like and lamp architecture a bit similar, I do not understand the Android, just feel a bit similar, the master can point out the difference, the younger brother here greatly thanks

From top down:

Android Architecture--------------Description--------Lamp Architecture

1. Application--------Specific application--------Web application

2. Application framework----Java-------------PHP language and libraries

3. System Runtime:----Virtual machine---------Web server

⒋linux Kernel:---operating system-------the lamp architecture L

How PHP performs/executes the process

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.