PHP kernel SAPI Explore instance sharing

Source: Internet
Author: User
As a simple and powerful language, PHP provides many of the language features that are available to the Web. From the practice, after the weak type variable principle inquiry, Wang Shuai will continue to take you to understand some common parts of PHP kernel, this issue is SAPI in-depth understanding.

SAPI is an abbreviation for the server Application programming Interface (Application programming interface for servers). PHP provides a set of interfaces through SAPI for data interaction between the application and the PHP kernel.

In a nutshell, just like the input and output of a function, we execute a piece of PHP code from the Linux command line, essentially the Linux shell passing in a set of parameters via PHP SAPI, and the process that the Zend engine executes, returns to the shell, and is displayed by the shell. Similarly, through Apache call PHP, through the Web server to SAPI incoming data, Zend engine executes, returned to Apache, by Apache display on the page.

Figure 1. PHP Frame composition

PHP offers many forms of interface, 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 5 forms commonly used, cli/cgi (command line), multiprocess (multi-process), multithreaded (multithreading), fastcgi, and embedded (inline).

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

String Php_sapi_name (void)

PHP Run and load

Regardless of which SAPI is used, before and after PHP executes the script, it contains a series of events: module init (MINT) and shutdown (mshutdown), Request init (RINT), and Shutdown (Rshutdown). The first phase is the PHP module initialization phase (MINT), which initializes the extended internal variables, allocates resources, and registers the resource processor, which executes only once during the entire PHP instance lifecycle.

What is a PHP module? With the above PHP frame composition, you can use the Get_loaded_extensions function in PHP to view all compiled and loaded modules/extensions, equivalent to php-m in CLI mode.

Take PHP's memcached extension source code 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;  /* Performs some similar initialization operations */  return SUCCESS;}

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

Php_rinit_function (memcached) {/* Performs some initialization of the request */  return SUCCESS;}

In the third phase, after the request processing is completed, the php_rshutdown_function is called for recycling, which is the request shutdown function for each extension, which performs the final cleanup work. The Zend engine performs the cleanup process, garbage collection, and execution of unset for each variable used during the previous request. The request completion may be performed to the completion of the script, or it may be called the die () or exit () function to complete

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

Php_mshutdown_function (memcached) {/* Perform destruction work on the module */unregister_ini_entries (); return SUCCESS;}

Common mode of Operation

There are five common SAPI modes:

    • CLI and CGI mode (single process mode)

    • Multi-process Mode

    • Multithreaded mode

    • fastcgi mode

    • Embedded

1. cli/cgi mode

Both the CLI and CGI are in single-process mode, and the life cycle of PHP is completed in one request. That is, each time the PHP script executes, the second part of the four int and shutdown events will be executed.

Figure 2. CGI/CLI life cycle

2. Multi-process mode (multiprocess)

Multi-process mode can be built into the Web server PHP, PHP can be compiled into Apache under the Prefork mpm mode and APXS module, when Apache started, will fork many child processes, each child process has its own independent process address space.

Figure 3. Multi-process mode life cycle

In a child process, PHP's life cycle is after the call to mint starts, the execution of multiple requests (Rint/rshutdown), after the Apache shutdown or the end of the process, will call Mshutdown for the recycling phase.

Figure 4. The life cycle of a multi-process

In a multi-process model, each child process is run independently, without code and data sharing, so that one child process terminates the exit and rebuilds without affecting the stability of the other child processes.

3. Multithreaded mode (multithreaded)

Apache2 's worker MPM employs a multithreaded model that creates multiple threads under one process and executes in the same process address space.

Figure 5. Multi-threaded life cycle

4. FastCGI mode

In our use of NGINX+PHP-FPM is the fastcgi mode, fastcgi is a special CGI mode, is a kind of resident process type of CGI, after running can fork multiple processes, without spending time dynamic fork subprocess, You do not need to call Mint/mshutdown every time you request it. PHP manages and dispatches FastCGI's process pool through PHP-FPM. Nginx and PHP-FPM communicate through a local TCP socket and a UNIX socket.

Figure 6. FastCGI Mode life cycle

The PHP-FPM process Manager itself initializes and starts multiple CGI interpreter processes waiting for requests from nginx. When the client request reaches PHP-FPM, the manager chooses to process the CGI process, and Nginx sends the CGI environment variable and the standard input to a php-cig subprocess. After the php-cgi process finishes processing, the standard output and error information is returned to Nginx, and when the php-cgi child process closes the connection, the request processing is complete. The php-cgi child process waits for the next connection.

You can imagine how much the CGI system costs. Every Web request PHP must re-parse php.ini, load all extensions, and start all of the data structures. With fastcgi, all of this occurs only once when the process is started. In addition, persistent connections to databases and memcache can work.

5. Inline mode (Embedded)

Embed SAPI is a special kind of SAPI that allows you to invoke PHP-provided functions in a C + + language. This SAPI is run in the same mode as the CLI mode, as per module init = Request init = Request + Request Shutdown = module Shutdown.

Embed SAPI can invoke the PHP rich class library, but also can implement advanced gameplay, such as can see PHP opcode (php execution Intermediate code, Zend engine instructions, generated by PHP code).

For details, see: http://www.laruence.com/2008/09/23/539.html

Operating mechanism of SAPI

We take CGI as an example to see how the SAPI works.

Static Sapi_module_struct Cgi_sapi_module = {"cgi-fcgi",/* output to Php_info () using */"cgi/fastcgi", /* Pretty name */php_cgi_startup,/* Startup This function is called first when the SAPI is initialized */php_module_s              Hutdown_wrapper,/* 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 will be called at the beginning of each request, it will do initialization, resource allocation */sapi_cgi_deactivate,/* Deactivate this function will be called at the end of each request, it is used to ensure that all the data All get released */Sapi_cgi_ub_write,/* unbuffered write does not cache writes (unbuffered write), which is used to output data to SAPI external */Sapi_c     Gi_flush,/* Flush flush output, implemented in CLI mode by using the C-language library function Fflush */NULL,/* Get UID */   Sapi_cgi_getenv,/* getenv find environment variables by name */php_error,/* Error handler register error handling function */NULL,/* Header handler PHP call header () is called */sapi_cgi_send_headers,/* s End Headers Handler Send headerInformation */NULL,/* Send header handler sends a separate header message */Sapi_cgi_read_post,/* rea      D Post data when the requested method is post, the program obtains the post, writes the $_post array/*/sapi_cgi_read_cookies,/* Read cookies to get the cookie value */  Sapi_cgi_register_variables,/* Register server variables add environment variable to $_server */sapi_cgi_log_message,/* log  Message Output error message */NULL,/* Get request time */NULL,/* Child Terminate */standard_sapi_module_properties};

As the above code shows, PHP's SAPI is like object-oriented base classes, SAPI.h and SAPI.C contain functions that are abstract base class declarations and definitions, the SAPI pattern used by each server, inherits the base class, and re-defines the subclass of the base class method.

Summarize

PHP's SAPI is a standard set of interfaces provided by the Zend engine, and by registering initialization, destruction, input, and output interfaces, we can either run the application on the Zend engine or embed PHP in an Apache-like Web server. PHP Common SAPI mode has five kinds, cgi/cli mode, multi-process mode, multi-threaded mode, fastcgi mode and embedded mode.

Understanding PHP's SAPI mechanism is significant, helping us understand the life cycle of PHP and understanding how to better write extensions to PHP in C + +, and find ways to improve system performance over the life cycle.

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.