PHP Execution principle/Execution Process

Source: Internet
Author: User
Tags sapi

For more information, see the following:

Storm blog http://www.laruence.com/2008/08/12/180.html

Baidu R & D center's blog http://stblog.baidu-tech.com /? P = 763

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

Introduction
Let's take a look at the following process:

    • We have never started PHP-related processes manually. It runs with Apache startup;
    • PHP uses mod _PHP5. The so module is connected to Apache (specifically, SAPI, that is, the server applicationProgramProgramming Interface );
    • PHP has three modules: kernel, Zend engine, and extension layer;
    • The PHP kernel is used to process requests, file streams, error handling, and other related operations;
    • The Zend engine (ze) is used to convert the source file to the machine language, and then run it on the virtual machine;
    • The extension layer is a set of functions, class libraries, and streams. php uses them to perform certain operations. For example, we need MySQL extension to connect to the MySQL database;
    • When ze executes the program, it may need to connect several extensions. Then ze gives control to the extension and returns the control after processing the specific task;
    • Finally, ze returns the program running result to the PHP kernel. It then delivers the result to the SAPI layer and finally outputs the result to the browser.

In-depth discussion
And so on. The above process is just a simple version. Let's dig deeper to see what happened behind the scenes.

    • After Apache is started, the PHP interpreter starts;
    • PHP can be started in two steps;
    • The first step is to initialize some environment variables, which will take effect throughout the SAPI lifecycle;
    • The second step is to generate only some variable settings for the current request.

Step 1 of PHP startup
I don't know what the first step is? Don't worry. Let's discuss it in detail. Let's take a look at the first step, which is also the main step. Remember that the first step of operation occurs before any request arrives.

    • After Apache is started, the PHP interpreter starts;
    • PHP calls the minit methods of each extension to switch these extensions to the available state. LookPHPWhich extensions are opened in the. ini file;
    • Minit indicates "module initialization ". Each module defines a set of functions and class libraries to process other requests.

A typical minit method is as follows:
Php_minit_function (extension_name ){
/* Initialize functions, classes etc */
}
Step 2 of PHP startup

    • When a page request occurs, the SAPI layer gives control to the PHP layer. Therefore, PHP sets the environment variables required to reply to this request. It also creates a variable table to store the names and values of variables generated during execution.
    • PHP calls the rinit method of each module, that is, "request initialization ". A typical example is the session module rinit.PHPWhen the session module is enabled in. ini, the $ _ session variable will be initialized when the rinit of this module is called and the related content will be read;
    • The rinit method can be considered as a preparation process, which is automatically started 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 */
}
Step 1 of PHP Shutdown
Like PHP startup, PHP shutdown is also divided into two steps:

    • Once the page is executed (whether it is executed at the end of the file or aborted using the exit or die function), PHP starts the cleanup program. It calls 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 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 */
}
Step 2 of PHP disabling
Finally, all requests have been processed, and the SAPI is also ready to be closed. php starts to execute Step 2:

    • PHP calls the mshutdown method of each extension, which is the last chance 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 lifecycle is over. Note that "Start Step 1" and "close step 2" are performed only when the server does not have a request ".

 

The following are some illustrations!

Working principle of PHP underlying layer

Figure 1 PHP Structure

From the figure, we can see that PHP is a layer-4 system from bottom to top.

① Zend Engine

Zend is implemented in pure C, which is the kernel part of PHP.CodeTranslation (a series of compilation processes such as lexical and Syntax Parsing) implements opcode processing, corresponding processing methods, and basic data structures (such as hashtable and OO) memory Allocation and Management, and the provision of corresponding API methods for external calls are the core of everything, and all peripheral functions are implemented around Zend.

② Extensions

Around the Zend engine, extensions provides various basic services in a component-based manner. Our common built-in functions (such as the array series) and Standard libraries are implemented through extension, you can also implement your own extension as needed to achieve function expansion and performance optimization (for example, the PHP middle layer being used by the post bar and Rich Text parsing are typical applications of extension ).

③ SAPI

The full name of SAPI is the server application programming interface, that is, the server application programming interface. SAPI enables PHP to interact with peripheral data through a series of hook functions, which is a very elegant and successful design of PHP, through SAPI, PHP itself and upper-layer applications are successfully decoupled and isolated. php can no longer consider how to be compatible with different applications, and the application itself can implement different processing methods based on its own characteristics. This topic will be introduced later in SAPI

④ Upper-layer applications

This is the PHP program we usually write and various application modes are obtained through different SAPI methods, such as implementing Web applications through webserver and running scripts under the command line.

Architecture:

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

The middle layer (SAPI) isolates web server and PHP

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

If PHP is a car

The car's framework is Php itself.

Zend is a car engine)

The components below ext are the wheels of a car.

SAPI can be seen as a highway, and vehicles can run on different types of Roads

The execution of a PHP program is that a car runs on the road.

Therefore, we need an engine with excellent performance + a proper wheel + a correct runway.

Relationship between APACHE and PHP

Apache's PHP Parsing is done through the PHP module in many modules.

To integrate PHP into Apache, you also need to make some necessary settings for Apache. Here, we will take the mod_php5 SAPI running mode of PHP as an example. The SAPI concept will be explained in detail later.

Assume that the installed versions are apache2 and PhP5. Edit the main configuration file HTTP. conf of Apache and add the following lines to it:

In Unix/Linux:

Loadmodule php5_module modules/mod_php5.so

Addtype application/X-httpd-PHP. php

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

In Windows:

Loadmodule php5_module D:/PHP/php5apache2. dll

Addtype application/X-httpd-PHP. php

Note: D:/PHP/php5apache2. dll is the installation location of the php5apache2. dll file in windows.

These two configurations tell the Apache server that any URL user request received later uses PHP as the suffix and needs to be processed by calling the php5_module module (mod_php5.so/php5apache2. dll.

Apache Lifecycle

Apach request processing process

Detailed explanation of Apache request processing cycle 
What have been done in the 11 phases of Apache request processing cycle?

1. Post-read-request stage

In the normal request processing process, this is the first stage in which the module can insert hooks. This phase can be used by modules that want to process requests very early.

2. Uri translation stage
Apache's main work in this phase: map the request URL to the local file system. The module can insert hooks at this stage to execute its own ing logic. Mod_alias uses this phase of work.

3. Header Parsing stage
In this phase, Apache checks the request header. This hook is rarely used because the module can execute the task of checking the request header at any point in the request processing process. Mod_setenvif uses this phase of work.

4. Access control stage
Apache's main work in this phase: Check whether the requested resources are allowed to be accessed Based on the configuration file. Apache's Standard logic allows and denies commands. Mod_authz_host is used in this phase.

5. authentication stage
Apache's main work in this phase: authenticate users according to the policies set in the configuration file, and set the user name area. The module can insert hooks at this stage to implement an authentication method.

6. Authorization stage
Apache's main work in this phase: checks whether Authenticated Users are allowed to perform request operations based on the configuration file. The module can insert hooks at this stage to implement a user permission management method.

7. MIME type checking stage
Apache's main work in this phase: determine the content processing functions to be used based on the rules related to the MIME type of the requested resource. The standard modules mod_negotiation and mod_mime implement this hook.

8. fixup stage
This is a common stage that allows a module to run any necessary processing flow before the content generator. Similar to post_read_request, This Is A hook that can capture any information and is also the most commonly used hook.

9. response stage
Apache's main work in this phase: generate the content returned from the client and send an appropriate response to the client. This stage is the core part of the entire processing process.

10. Logging stage
Apache's main work in this phase: record transactions after replying to a client. The module may modify or replace Apache standard logging.

11. Cleanup stage
The main work of Apache in this phase: clean up the environment left after the transaction processing of this request is completed, such as processing files, directories, or closing socket, etc, this is the last stage of Apache request processing.

Lamp architecture:

From bottom to top 4:

① Liunx is the underlying operating system

② Apache server, which belongs to the secondary server, communicates with Linux and PHP

③ PHP: belongs to the server.Programming Language, Associate with Apache through the php_module Module

④ MySQL and other Web Services: it is an application service. It is associated with MySQL through the extensions external modules of PHP.

Android Architecture

The lamp and Android architecture diagram is similar to the lamp architecture. I don't know about Android, but I feel a little similar. Experts can point out the differences. Thank you very much.

From top to bottom:

Android architecture -------------- description -------- lamp Architecture

1. Application -------- specific application -------- Web Application

2. Application Framework ---- Java ------------- PHP language and Library

3. System Runtime Library: ---- Virtual Machine --------- Web Server

Customized Linux kernel: --- operating system ------- L in lamp Architecture

 

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.