Deep understanding of PHP kernel (2) and SAPI exploration

Source: Internet
Author: User
Tags sapi
This article mainly introduces the related information about the SAPI inquiry of PHP kernel (II). For more information, see the previous article ), I believe you have learned more or less through this article. you will continue to pay attention to this article on php kernel knowledge.

SAPI is the abbreviation of Server Application Programming Interface (Server Application Programming Interface. PHP provides a set of interfaces through SAPI for data interaction between the supply and the PHP kernel.

To put it simply, just like the input and output of functions, we execute a piece of PHP code through the Linux command line. in essence, the Linux Shell passes in a set of parameters through the SAPI of PHP, after the Zend Engine is executed, it is returned to the shell, which is displayed by the shell. Similarly, Apache calls PHP and transmits data to SAPI through the Web server. after the Zend Engine is executed, Apache returns the data to Apache, which is displayed on the page.


. PHP architecture

PHP provides many forms of interfaces, including apache, apache2filter, apache2handler, caudium, cgi, cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd pi3web, roxen, thttpd, tux and webjames. However, there are only five common forms: CLI/CGI (command line), Multiprocess (multi-process), Multithreaded (multi-thread), FastCGI, and Embedded (Embedded ).

PHP provides a function to view the current SAPI type:

The code is as follows:


String php_sapi_name (void)

PHP running and loading

No matter which SAPI is used, before and after PHP executes the script, it contains a series of events: Module Init (MINT), Shutdown (MSHUTDOWN), Request Init (RINT), and Shutdown (RSHUTDOWN ). The first stage is the PHP module initialization phase (MINT). It can initialize internal variables for expansion, allocate resources, and register resource processors. this process is only executed once throughout the lifecycle of the PHP instance.

What is the PHP module? Through the above PHP architecture diagram, you can use the get_loaded_extensions function in PHP to view all the compiled and loaded modules/extensions, which is equivalent to php-m in CLI mode.

Take the Memcached extension source code of PHP as an example:

PHP_MINIT_FUNCTION (memcached) {zend_class_entry ce; memcpy (& memcached_object_handlers, zend_get_std_object_handlers (), sizeof (zend_object_handlers); handler = NULL; /* some similar initialization operations */return SUCCESS ;}

The second stage is the request initialization stage (RINT). after the module is initialized and activated, the PHP runtime environment is created, and the RINT functions registered by all modules are called to call the initialization functions of each extension request, set specific environment variables, allocate resources, or execute other tasks, such as review.

PHP_RINIT_FUNCTION (memcached) {/* execute some Request Initialization */return SUCCESS ;}

In the third stage, after the request processing is complete, PHP_RSHUTDOWN_FUNCTION will be called for recycling. this is the final cleaning of every extended request to close the function. The Zend engine executes the cleanup process, garbage collection, and unset for each variable used during the previous request. The request may be completed by executing the script or calling the die () or exit () function.

In the fourth stage, when the lifecycle of PHP is over, PHP_MSHUTDOWN_FUNCTION recycles the module. this is the function for each extended module to close its own kernel subsystem.

PHP_MSHUTDOWN_FUNCTION (memcached) {/* execute the module destruction work */UNREGISTER_INI_ENTRIES (); return SUCCESS ;}

Common running modes

There are five common SAPI modes:

CLI and CGI modes (single process mode)
Multi-process mode
Multithreading mode
FastCGI mode
Embedded

1. CLI/CGI mode

CLI and CGI are in single-process mode, and the lifecycle of PHP is completed in one request. That is to say, each execution of the PHP script will execute the four INT and Shutdown events described in the second part.

. CGI/CLI lifecycle

2. Multiprocess)

In the multi-process mode, PHP can be built into the Web Server. PHP can be compiled into the prefork MPM mode and APXS module under Apache. After Apache is started, many sub-processes will be fork, each sub-process has its own independent process address space.


. Multi-process mode lifecycle

In a sub-process, the life cycle of PHP is to execute multiple requests (RINT/RSHUTDOWN) after the MINT is called for startup. After Apache is disabled or the process ends, will call MSHUTDOWN for the recovery phase.

. Multi-process lifecycle

In the multi-process model, each sub-process runs independently without code or data sharing. Therefore, the termination and re-generation of a sub-process will not affect the stability of other sub-processes.

3. Multithreaded)

The Worker MPM of Apache2 adopts a multi-threaded model. multiple threads are created under a process and executed in the same process address space.


. Multithreading lifecycle

4. FastCGI mode

The Nginx + PHP-FPM we use is FastCGI mode, Fastcgi is a special CGI mode, is a resident process type CGI, after running can Fork multiple processes, you do not need to take the time to dynamically Fork sub-processes or call MINT/MSHUTDOWN for each request. PHP manages and schedules FastCGI process pools through PHP-FPM. Nginx and PHP-FPM communicate with each other through a local TCP Socket and Unix Socket.


. FastCGI mode lifecycle

The PHP-FPM process manager initializes itself and starts multiple CGI interpreter processes to wait for requests from Nginx. When the client request reaches the PHP-FPM, the manager selects a CGI process for processing, Nginx sends the CGI environment variables and standard input to a PHP-CIG sub-process. After the PHP-CGI sub-process processing is complete, the standard output and error information is returned to Nginx, when the PHP-CGI sub-process closes the connection, the request processing is complete. The PHP-CGI sub-process waits for the next connection.

You can imagine the system overhead of CGI. Every Web request, PHP, must re-parse php. ini, load all extensions, and start all data structures. With FastCGI, all of these occur only once when the process starts. In addition, continuous connections between databases and Memcache can work.

5. Embedded mode (Embedded)

Embed SAPI is a special SAPI that allows you to call functions provided by PHP in C/C ++. In the same SAPI and CLI modes, run in Module Init => Request Shutdown => Module Shutdown mode.

Embed SAPI can call a variety of PHP class libraries or implement advanced gameplay. for example, you can view php opcode (intermediate code executed by PHP, Zend Engine command, generated by PHP code ).

See http://www.bitsCN.com/article/74641.htm for details

SAPI running mechanism

Let's take CGI as an example to look at the SAPI running mechanism.

Static sapi_module_struct cgi_sapi_module = {"cgi-fcgi",/* output to php_info () using */"CGI/FastCGI",/* pretty name */php_cgi_startup, /* startup when the SAPI is initialized, the function */php_module_shutdown_wrapper will be called first,/* shutdown to close the function Packer, which is used to release the data structure and memory of all SAPIs, call php_module_shutdown */sapi_cgi_activate,/* activate. This function is called at the beginning of each request. it initializes and allocates resources */sapi_cgi_deactivate, /* deactivate this function will be called at the end of each request. it is used to ensure that all data is released */sapi_cgi_ub_write,/* unbuffered write non-cached write operations (unbuffered write ), it is used to output data externally to SAPI */sapi_cgi_flush,/* flush to refresh the output. in CLI mode, it is implemented by using the library function fflush in C language */NULL, /* get uid */sapi_cgi_getenv,/* getenv searches for the environment variable by name */php_error,/* error handler registers the error processing function */NULL, /* header handler PHP is called when header () is called */sapi_cgi_send_headers,/* send headers handler sends header information */NULL, /* send header handler sends a separate header information */sapi_cgi_read_post,/* read POST data when the request method is POST, the program obtains POST data, write $ _ POST array */sapi_cgi_read_cookies,/* read Cookies to get the Cookie value */sapi_cgi_register_variables,/* register server variables add the environment variable */sapi_cgi_log_message to $ _ SERVER, /* Log message output error message */NULL,/* Get request time */NULL,/* Child terminate */STANDARD_SAPI_MODULE_PROPERTIES };

As can be seen from the code above, PHP's SAPI is like a basic class in object-oriented, SAPI. h and SAPI. c contains the declaration and definition of abstract base classes. the SAPI mode used by each server inherits the base class and the subclass of the base class method is redefined.

Summary

PHP's SAPI is a set of standard interactive interfaces provided by the Zend Engine. by registering initialization, structure, input, output, and other interfaces, we can run the application program on the Zend Engine, you can also embed PHP into a Web Server similar to Apache. PHP has five common SAPI modes: CGI/CLI mode, multi-process mode, multi-thread mode, FastCGI mode, and embedded mode.

Understanding the SAPI mechanism of PHP is of great significance. it helps us understand the lifecycle of PHP and how to better compile extensions for PHP through C/C ++, and find a way to improve system performance in the lifecycle.

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.