Working principle of PHP underlying layer

Source: Internet
Author: User
Tags sapi

Introduction
Let's take a look at the following process:
We have never started PHP-related processes manually. It runs with Apache startup;
PHP is connected to Apache through the mod_php5.so module (specifically, SAPI, that is, the server application programming 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. See what extensions are opened in the php. 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 classic example is the Session module RINIT. when 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 and is the kernel part of php. It translates php code (a series of compilation processes such as lexical and Syntax Parsing) it can process and implement corresponding processing methods, implement basic data structures (such as hashtable and oo), allocate and manage memory, and provide corresponding api methods for external calls, is 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: it belongs to the server programming language and is associated 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.
Author: ibmfahsion

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.