Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand SAPI in PHP kernel

2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "how to understand SAPI in the PHP kernel". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

SAPI is an abbreviation for Server Application Programming Interface (Server Application programming Interface). PHP provides a set of interfaces through SAPI for data exchange between applications and the PHP kernel.

To put it simply, just like the input and output of a function, we execute a piece of PHP code through the Linux command line, which is essentially a process that the Shell of Linux passes in a set of parameters through the SAPI of PHP, and the Zend engine executes it and returns it to shell, which is displayed by shell. Similarly, PHP is called through Apache, and data is passed in to SAPI through the Web server, which, after execution by the Zend engine, is returned to Apache and displayed by Apache on the page.

Figure 1. PHP architecture diagram

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. But there are only five commonly used forms, CLI/CGI (command line), Multiprocess (multiprocess), Multithreaded (multithreading), FastCGI, and Embedded (embedded).

PHP provides a function to view the current SAPI interface type:

The copy code is as follows:

String php_sapi_name (void)

Running and loading of PHP

No matter which SAPI is used, there is a series of events before and after PHP executes the script: Init (MINT) and Shutdown (MSHUTDOWN) for Module, Init (RINT) and Shutdown (RSHUTDOWN) for Request. The first phase is the PHP module initialization phase (MINT), which initializes extended internal variables, allocates resources, and registers resource processors, which is performed only once throughout the life cycle of the PHP instance.

What is a PHP module? With the PHP architecture diagram above, you can use the get_loaded_extensions function in PHP to view all compiled and loaded modules / extensions, which are 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)); memcached_object_handlers.clone_obj = NULL; / * performed some similar initialization operations * / return SUCCESS;}

The second stage is the request initialization phase (RINT). After the module is initialized and activated, the PHP runtime environment is created, and the RINT functions registered by all modules are called, each extended request initialization function is called, specific environment variables are set, resources are allocated, or other tasks such as auditing are performed.

PHP_RINIT_FUNCTION (memcached) {/ * perform some initialization of the request * / return SUCCESS;}

In the third stage, after the request processing is completed, PHP_RSHUTDOWN_FUNCTION is called for recycling, which closes the request function for each extension and performs the final cleanup work. The Zend engine performs cleanup, garbage collection, and unset for each variable used during the previous request. The request may be completed by execution until the script is completed, or by calling the die () or exit () function

In the fourth phase, when the PHP life cycle ends, PHP_MSHUTDOWN_FUNCTION reclaims the module, which is a module shutdown function for each extension that shuts down its own kernel subsystem.

PHP_MSHUTDOWN_FUNCTION (memcached) {/ * perform the destruction of the module * / UNREGISTER_INI_ENTRIES (); return SUCCESS;}

Common operation mode

There are five common SAPI modes:

CLI and CGI mode (single-process mode)

Multi-process mode

Multithreaded mode

FastCGI mode

Embedded system

1. CLI/CGI mode

Both CLI and CGI are in single-process mode, and the life cycle of PHP is completed in a single request. That is, each time the PHP script is executed, the four INT and Shutdown events described in part 2 are executed.

Figure 2. CGI/CLI lifecycle

two。 Multi-process mode (Multiprocess)

PHP can be built into Web Server in multi-process mode, and PHP can be compiled into prefork MPM mode and APXS module under Apache. When Apache starts, it will fork many child processes, each of which has its own independent process address space.

Figure 3. Multi-process mode life cycle

In a child process, the life cycle of a PHP is to call MINT to start, execute multiple requests (RINT/RSHUTDOWN), and then call MSHUTDOWN for the recycling phase after the Apache is shut down or the process ends.

Figure 4. The life cycle of multiple processes

In the multi-process model, each child process runs independently, and there is no code and data sharing, so the termination, exit and reconstruction of one child process will not affect the stability of other child processes.

3. Multithreaded mode (Multithreaded)

Apache2's Worker MPM uses a multithreaded model to create multiple threads under one process and execute them in the same process address space.

Figure 5. Multithreaded life cycle

4. FastCGI mode

In the Nginx+PHP-FPM we use is FastCGI mode, Fastcgi is a special CGI mode, is a resident process type of CGI, after running can Fork multiple processes, do not need to spend time dynamic form child process, also do not need to call MINT/MSHUTDOWN every request. PHP manages and schedules the process pool of FastCGI through PHP-FPM. Nginx and PHP-FPM communicate through local TCP Socket and Unix Socket.

Figure 6. FastCGI schema lifecycle

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

You can imagine the system overhead of CGI. Each Web request PHP must reparse the php.ini, load all extensions, and initialize all data structures. With FastCGI, all of this happens only once when the process starts. In addition, a continuous connection between the database and Memcache works.

5. Embedded mode (Embedded)

Embed SAPI is a special kind of SAPI that allows functions provided by PHP to be called in the Cmax Cobb + language. This SAPI, like the CLI mode, runs in the same mode as Module Init = > Request Init = > Request = > Request Shutdown = > Module Shutdown.

Embed SAPI can call PHP's rich class libraries or implement advanced games, such as viewing PHP's OPCODE (intermediate code executed by PHP, instructions from the Zend engine, generated by PHP code).

For more information, please see: https://www.jb51.net/article/74641.htm

The operating Mechanism of SAPI

Let's take CGI as an example and take a look at how SAPI works.

Static sapi_module_struct cgi_sapi_module = {"cgi-fcgi", / * output to php_info () using * / "CGI/FastCGI", / * pretty name * / php_cgi_startup, / * startup when SAPI is initialized, the function * / php_module_shutdown_wrapper is first called, / * shutdown closes the function wrapper, which is used to release all SAPI data structures, memory, etc. Call php_module_shutdown * / sapi_cgi_activate, / * activate this function is called at the beginning of each request, it initializes, resource allocation * / sapi_cgi_deactivate, / * deactivate this function is called at the end of each request, it is used to ensure that all data is released * / sapi_cgi_ub_write, / * unbuffered write uncached write operations (unbuffered write) It is used to output data to SAPI external * / sapi_cgi_flush, / * flush refresh output In CLI mode, the library function fflush of C language is used to implement * / NULL, / * get uid * / sapi_cgi_getenv, / * getenv looks up the environment variable * / php_error according to name, / * error handler registers the error handling function * / NULL, / * header handler PHP is called * / sapi_cgi_send_headers when calling header (), / * send headers handler sends header information * / NULL / * send header handler sends a separate header message * / sapi_cgi_read_post, / * read POST data when the request method is POST The program gets POST data, writes the $_ POST array * / sapi_cgi_read_cookies, / * read Cookies gets the cookie value * / sapi_cgi_register_variables, / * register server variables adds the environment variable * / sapi_cgi_log_message to $_ SERVER, / * Log message outputs error messages * / NULL, / * Get request time * / NULL, / * Child terminate * / STANDARD_SAPI_MODULE_PROPERTIES}

As can be seen from the above code, the SAPI of PHP is like an object-oriented base class, the functions contained in SAPI.h and SAPI.c are the declaration and definition of the abstract base class, and the SAPI schema used by each server inherits this base class and redefines the subclass of the base class method.

Summary

SAPI of PHP is a set of standard interactive interfaces provided by Zend engine. By registering initialization, destructing, input, output and other interfaces, we can run applications on Zend engine, or embed PHP into Web Server similar to Apache. There are five common SAPI modes in PHP: CGI/CLI mode, multi-process mode, multi-thread mode, FastCGI mode and embedded mode.

It is of great significance to understand the SAPI mechanism of PHP, to help us understand the life cycle of PHP, and to understand how to better write extensions for PHP through Cplink +, and find ways to improve system performance in the life cycle.

That's all for "how to understand SAPI in the PHP kernel". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report