In-depth understanding of PHP operating mode

Source: Internet
Author: User
Tags apache error log fpm php source code

This article is a detailed analysis of the PHP operating mode introduced, the need for a friend reference PHP operating mode has 4 minutes:
1) CGI Universal Gateway Interface (Common Gateway Interface))
2) fast-cgi resident (long-live) type CGI
3) CLI command line run (Interface)
4) Web module mode (module mode for Web server running like Apache)
1.CGI (Common Gateway Interface)
CGI is the Universal Gateway Interface (Common Gateway Interface), it is a program, the popular CGI is like a bridge, the Web page and the Web server to connect the execution program, it takes HTML received instructions to the server's execution program, The results of the server execution program are then returned to the HTML page. CGI has excellent cross-platform performance and can be implemented on almost any operating system. CGI is already a relatively old pattern, and it has seldom been used in recent years.

For each user request, the child process of the CGI is created first, then the request is processed, and the child process is finished after processing, which is the Fork-and-execute mode. When the user requests a very long time, will be heavily crowding out the system resources such as memory, CPU times, resulting in low performance. So how many CGI sub-processes are there for the CGI server, and the sub-process loading is the main reason for the poor CGI performance.
If you do not want to embed PHP into the server-side software (such as Apache) as a module installation, you can choose to install in CGI mode. Or use PHP for different CGI wrappers to create a secure chroot and SETUID environment for your code. So that each client requests a PHP file, the Web server calls Php.exe (Php.exe,linux is PHP) to interpret the file, and then returns the result of the explanation as a Web page to the client. This installation typically installs the PHP executable file to the Web server's Cgi-bin directory. CERT Proposal CA-96.11 recommends that you do not put any interpreter in the Cgi-bin directory.

The advantage of this approach is that the Web server and the specific program processing independent, clear structure, controllability, and the disadvantage is that if in the case of high access requirements, CGI process fork will become a large server burden, want to Like a hundreds of concurrent requests cause the server to fork out hundreds of processes to understand. This is why CGI has been saddled with poor performance and high resource consumption for notoriety reasons.

CGI mode installation:
CGI is an older model, and it's rarely used in years, so we're just trying to test it.
Installing the CGI mode requires commenting out
LoadModule Php5_module modules/libphp5.so this line. If you do not annotate this line go straight to handler mode. This is the module mode.
Then add the action in httpd.conf:
Action application/x-httpd-php/cgi-bin/
If php-cgi is not found in the/cgi-bin/directory. You can do it yourself from the bin inside of PHP.
Then restart Apache, and then open the test page to discover that the server API becomes: cgi/fastcgi. Description successfully switched to CGI mode.
questions:
1) If the CGI program cannot be executed in the/usr/local/httpd/cgi-bin/, encountering a 403 or 500 error
Opening the Apache error log has the following hint: Permission denied:exec of
You can check the properties of the CGI program, as defined in the Linux contexts file, and the/usr/local/httpd/cgi-bin/must be the httpd_sys_script_exec_t attribute. By Ls-z, if not, change it with the following command: Chcon-t httpd_sys_script_exec_t/var/www/cgi-bin/*.cgi If it is a CGI in a virtual host, refer to question 2 to make it normal to use the normal function, The context of the CGI file is then set via Chcon
Httpd_sys_script_exec_t can be. Chcon-r-T httpd_sys_script_exec_t cgi-bin/
2) Apache error Hint: .... malformed header from script. Bad header=
Follow the prompts to indicate that there is a problem with the header, to see what the first sentence of the file output should resemble the following
Content-type:text/plain; charset=iso-8859-1\n\n
or content-type:text/html\n\n.
Note: Two blank lines are to be output after the declaration of a good content-type.
3) Apache error hint: Exec format error
The script interpreter is set incorrectly. The first line of the script should be in the form of ' #! interpreter path ', fill in the path of the script interpreter, if it is a Perl program, the Common path is: #!/usr/bin/perl or #!/usr/local/bin/perl if it is a PHP program, do not need to fill the interpreter path, The system will automatically find PHP.
2. FastCGI mode
FAST-CGI is an upgraded version of CGI, FastCGI like a resident (long-live) type of CGI, it can be executed all the time, as long as the activation, not each time to spend a fork once (this is the most criticized by CGI Fork-and-execute mode )。
How the FastCGI works is:
(1), the WEB server starts loading the FastCGI process Manager "PHP FastCGI process Manager is PHP-FPM (php-fastcgi processes manager)" (IIS ISAPI or Apache Module);
(2), the FASTCGI process manager itself initializes, initiates multiple CGI interpreter processes (multiple Php-cgi.exe visible in Task Manager) and waits for a connection from the Web server.
(3), when a client request arrives at Web server, the FASTCGI process manager selects and connects to a CGI interpreter. WEB server sends CGI environment variables and standard input to the FASTCGI child process php-cgi.
(4) After the fastcgi process finishes processing, the standard output and error messages are returned from the same connection to the Web Server. When the fastcgi child process closes the connection, the request is processed to completion. The fastcgi child process then waits and processes the next connection from the FASTCGI process Manager (running in webserver). In the normal CGI mode, php-cgi.exe exits here.
In CGI mode, you can imagine how slow CGI is usually. Every Web request PHP must re-parse php.ini, reload all DLL extensions, and initialize all data structures. With fastcgi, all of this occurs only once when the process is started. An additional benefit is that the persistent database connection (persistent connection) can work.
Advantages of fastcgi:
1) From a stability perspective, fastcgi is a separate process pool to run CGI, a single process is dead, the system can easily discard, and then reassign new processes to run the logic.
2) from a security perspective, FASTCGI supports distributed operations. FastCGI and the host server are completely independent, fastcgi how to down will not bring the server down.
3) From a performance standpoint, fastcgi separates the processing of the dynamic logic from the server, and the heavy-duty IO processing is left to the host server, so that the host server can focus on Io, and for a normal dynamic Web page, the logical processing may be only a small part, A lot of pictures and so static
FastCGI disadvantage: said the benefits, also say shortcomings. From my actual use, using FASTCGI mode is more suitable for the production environment of the server. But it's not very suitable for development machines. Because when using the Zend Studio debugger, the PHP process is returned with a 500 error on the page because fastcgi will think it timed out. This was very annoying, so I switched back to ISAPI mode on the development machine.
To Install the fastcgi mode:
Install Apache path is/usr/local/httpd/
Install PHP path is/usr/local/php/
1) Install mod_fastcgi
wget http://www.fastcgi.com/dist/mod_fastcgi-2.4.6.tar.gz
Tar zxvf mod_fastcgi-2.4.6.tar.gz
CD mod_fastcgi-2.4.6
CP MAKEFILE.AP2 Makefile
VI Makefile, edit top_dir =/usr/local/httpd
Make
Make install
When the installation is complete,
/usr/local/httpd/modules/One more file: mod_fcgid.so
2) Recompile PHP
./configure--prefix=/usr/local/php--enable-fastcgi--enable-force-cgi-redirect--disable-cli
Make
Make install
After compiling this, php-cgi in the bin directory of PHP is the PHP interpreter for fastcgi mode.
After the installation is successful, execute
Php-v output
PHP 5.3.2 (cgi-fcgi).
The output here is cgi-fcgi.
Note:
1. Compile parameters can not be added –WITH-APXS=/USR/LOCAL/HTTPD/BIN/APXS otherwise installed PHP execution file is the CLI mode
2 Output PHP 5.3.2 (CLI) If--DISABLE-CLI is not added at compile time

3) Configure Apache
Need to configure Apache to run PHP programs in fastcgi mode
VI httpd.conf
We use virtual machines to implement:
Copy the code code as follows:
#加载fastcgi模块
LoadModule Fastcgi_module modules/mod_fastcgi.so
#//static execution fastcgi initiated the 10 process
Fastcgiserver/usr/local/php/bin/php-cgi-processes 10-idle-timeout 150-pass-header HTTP_AUTHORIZATION
<virtualhost *:80>
#
Documentroot/usr/local/httpd/fcgi-bin
ServerName www.fastcgitest.com

scriptalias/fcgi-bin//usr/local/php/bin/#定义目录映射/fcgi-bin/instead of/usr/local/php/bin/
Options +execcgi
AddHandler fastcgi-script. php. fcgi #.php The end of the request is handled with php-fastcgi
AddType application/x-httpd-php. PHP #增加MIME类型
Action application/x-httpd-php/fcgi-bin/php-cgi #设置php-fastcgi's Processor:/usr/local/php/bin/php-cgi
<Directory/usr/local/httpd/fcgi-bin/>
Options Indexes execcgi
Order Allow,deny
Allow from all
</Directory>
</VirtualHost>
Or
Copy the code code as follows:
<ifmodule mod_fastcgi>scriptalias/fcgi-bin/"/usr/local/php/bin" #定义目录映射FastCgiServer/usr/local/php/bin/ Php-cgi-processes #配置fastcgi server,<directory "/usr/local/httpd/fcgi-bin/" >sethandler Fastcgi-scriptoptions Followsymlinksorder Allow,denyallow from All</directory>addtype application/x-httpd-php . php #增加MIME类型AddHandler php-fastcgi. PHP #.php the end of the request is to use PHP-FASTCGI to handle the action php-fastcgi/fcgi-bin/php-cgi # Setting up the PHP-FASTCGI processor
</IfModule>
4). Restart under Apache, view phpinfo If the server information is:
apache/2.2.11 (Unix) mod_fastcgi/2.4.6 or something like that means the installation was successful.
If a 403 error occurs, check to see if the/usr/local/httpd/fcgi-bin/has sufficient permissions.
Or
Copy the code code as follows:
<directory/>
Options FollowSymLinks
AllowOverride None
Order Deny,allow
Deny from all
</Directory>
Switch
Copy the code code as follows:
<directory/>
Options FollowSymLinks
AllowOverride None
Order Allow,deny
Allow from all
</Directory>
You can do it.
Ps-ef|grep php-cgi can see 10 fastcgi processes running on.
3. CLI mode
The CLI is the command-line run mode of PHP, you will often use it, but it may not be noticed (for example: we often use "php-m" in Linux to find PHP installed those extensions is the PHP command line running mode, interested students can input php-h to delve into the operation mode)
1. Let PHP run the specified file.
PHP script.php
Php-f script.php
Both of these methods (with or without the-f parameter) are able to run the script.php of the script. You can select any file to run, and the PHP scripts you specify do not have to be in. php as extensions, they can have arbitrary filenames and extensions.
2. Run the PHP code directly on the command line.
Php-r "Print_r (Get_defined_constants ());
When using this method, you should pay attention to the substitution of the shell variables and the use of quotation marks.
Note: Please read the above example carefully, when running the code without the start and end of the marker! With the-r parameter, these tokens are not required, plus they cause syntax errors.
3. Provide PHP code that needs to be run via standard input (stdin).
The above usage provides us with a very powerful feature that allows us to dynamically generate PHP code and run it from the command line, as shown in the example below:
$ some_application | Some_filter | php | Sort-u >final_output.txt
4. Module mode
Module mode is integrated in the form of a MOD_PHP5 module, at which point the MOD_PHP5 module is to receive PHP file requests from Apache, process the requests, and then return the processed results to Apache. If we configure the PHP module (MOD_PHP5) in its configuration file before Apache starts, the PHP module registers the apache2 ap_hook_post_config hook and starts the module to accept PHP file requests when Apache starts.

In addition to this boot-time loading, Apache modules can be loaded dynamically at runtime, which means that the server can be expanded without the need to re-compile the source code or even stop the server at all. All we need to do is send a signal to the server Hup or ap_sig_graceful notify the server to reload the module. But before we load it dynamically, we need to compile the module into a dynamic-link library. Dynamic loading at this time is the loading of the dynamic link library. The processing of the dynamic link library in Apache is done through the module Mod_so, so the Mod_so module cannot be dynamically loaded, it can only be statically compiled into Apache core. This means that it was launched with Apache.
How does Apache load the module? Let's take the MOD_PHP5 module mentioned earlier as an example. First we need to add a line to the Apache configuration file httpd.conf:
This is a running mode that we used to use with Apache servers in a Windows environment, and in a modular (DLL), PHP is started and run with a Web server. (It is an extension of Apache based on CGI, which accelerates the efficiency of PHP operation)
Copy the code code as follows:
LoadModule Php5_module modules/mod_php5.so
Here we use the LoadModule command, the first parameter of the command is the name of the module, the name can be found in the module implementation of the source code. The second option is the path where the module is located. If you need to load the module while the server is running, you can send the signal hup or ap_sig_graceful to the server, and once the signal is accepted, Apache will reload the module without restarting the server.

5.php operating mode in Nginx (nginx+ php-fpm)
There are two types of stack:ligthttpd+spawn-fcgi that are commonly used in fastcgi mode, and the other is NGINX+PHP-FPM (also available with spawn-fcgi).
A, as mentioned above, the two structures are used fastcgi to PHP support, so httpserver completely liberated, can better respond and concurrency processing. So lighttpd and Nginx have small, but powerful and efficient reputation.
B, the two can also distinguish a good or bad, spawn-fcgi because is part of the LIGHTTPD, so installed lighttpd generally will use spawn-fcgi to PHP support, But now there are users said LIGTTPD spwan-fcgi in high concurrent access, the above mentioned memory leak or even automatic restart fastcgi. That is: PHP script processor When the computer, this time if the user access, may appear white page (that is, PHP can not be parsed or error).

Another: First nginx is not like lighttpd itself with fastcgi (spawn-fcgi), so it is completely lightweight, must rely on a third-party fastcgi processor to be able to parse PHP, so in fact, it seems that nginx is very flexible, It can be connected with any third-party provider to parse the processor to enable parsing of PHP (easy to set up in nginx.conf). Nginx can use spwan-fcgi (need to install lighttpd together, but need to avoid the port for Nginx, some earlier blog has this aspect of the installation of the tutorial), but because spawn-fcgi with the above mentioned the user gradually discovered defects, Now slowly reduce the use of nginx+spawn-fcgi combination.

C, due to the shortcomings of the spawn-fcgi, there are now new third-party (currently, I heard that is trying to add to PHP core in the near future) of the PHP fastcgi processor, called PHP-FPM (specifically can Google). Compared with spawn-fcgi, it has the following advantages:
Since it was developed as a patch patch for PHP, the installation needs to be compiled with the PHP source code, that is, compiled into the PHP core, so in terms of performance should be excellent;
It also outperforms spawn-fcgi in handling high concurrency, at least not automatically restarting the FASTCGI processor. The specific algorithm and design can be understood by Google.

Therefore, as mentioned above because of the light weight and flexibility of nginx, so at present superior performance, more and more people gradually use this combination: NGINX+PHP/PHP-FPM
6. Summary
Currently in
Httpserver this piece of basic can see there are three kinds of stacks are more popular:
(1) APACHE+MOD_PHP5
(2) lighttp+spawn-fcgi
(3) NGINX+PHP-FPM
After all, the performance may be slightly better, but Apache is still the boss because of its rich modules and functions.  Some people test that NGINX+PHP-FPM may reach apache+mod_php5 5~10 times in high-concurrency situations, and now nginx+php-fpm use more and more. When we talk about CGI, we're talking about what the oldest Web server simply responds to the HTTP request from the browser and returns the HTML file stored on the server back to the browser, which is static HTML. Things are constantly evolving and websites are becoming more complex, so dynamic technology appears. But the server can not directly run php,asp such files, they can not do, outsourced to others, but to make a pact with the third, I give you what, and then you give me what, is to hold the request parameters sent to you, and then I receive your processing results to the client. The agreement is common Gateway Interface, or CGI. This protocol can be implemented with Vb,c,php,python. CGI is just an interface protocol, not a language at all. The following figure can see the process

Web server interacts with CGI programs

The Web server will determine how the data is routed to the CGI program based on the type of CGI program, typically passing data between the CGI programs through standard input/output streams and environment variables. As shown in the following:

The CGI program uses standard input (STDIN) and standard output (STDOUT) for input and output. The CGI program also uses environment variables to get input, and the operating system provides many environment variables that define the execution environment of the program, which the application can access. The Web server and CGI interface also set some environment variables to pass some important parameters to the CGI program. The CGI Get method also passes the data in the form to the CGI program through the environment variable query-string. Here are some common CGI environment variables:

Variable name Description
Content_Type The value of this environment variable indicates the MIME type of the information being passed. Currently, the environment variable content_type is generally: application/x-www-form-urlencoded, who says the data comes from an HTML form.
Content_length If the server and CGI program information is passed as post, this environment variable can be read from the standard input stdin bytes of valid data. This environment variable must be used when reading the input data.
Http_cookie The COOKIE content within the client.
Http_user_agent Provides customer browser information that contains a version number or other proprietary data.
Path_info The value of this environment variable represents the other path information immediately following the CGI program name. It often appears as a parameter to a CGI program.
Query_string If the server and CGI program information is passed in a get, the value of this environment variable even if the information is passed. This information is followed by the CGI program name, with a question mark '? ' in between. Separated.
Remote_addr The value of this environment variable is the IP address of the client sending the request, such as 192.168.1.67 above. This value is always present. And it is a unique identifier that Web clients need to provide to the Web server, which can be used in a CGI program to differentiate between different Web clients.
Remote_host The value of this environment variable contains the host name of the client that sent the CGI request. If you do not support the query, you do not need to define this environment variable.
Request_method Provides the method that the script is called. For scripts that use the http/1.0 protocol, only get and POST make sense.
Script_filename The full path of the CGI script
Script_name The name of the CGI script
server_name This is the host name, alias, or IP address of your WEB server.
Server_software The value of this environment variable contains the name and version number of the HTTP server that called the CGI program. For example, the value above is apache/2.2.14 (Unix)

An example

With all that said, you may feel bored, and writing a small program may be better understood. LIGHTTPD + CGI, write CGI program in C language.

LIGHTTPD Configure CGI, open cgi.conf, Cgi.assign = (". CGI" = "") to set the extension and interpreter for the CGI module. For the purposes of this statement, the CGI module's extension is ". CGI" and the CGI module does not require a special interpreter to execute. Because writing in C is an executable file.

Here is the TEST.C code:

#include "stdio.h" #include "stdlib.h" #include <string.h>int main () {     char *data;     data = getenv ("query_string");     puts (data);     printf ("Hello cgi!");     return 0;}

Build the executable file into the directory of your server configuration program

GCC Test.c-o test.cgi

Access: Http://localhost/test.cgi?a=b&c=d results are:

A=b&c=dhello cgi!

Obtain the content submitted by the Get method through the environment variable "query_string", if you want to get the content of the post submission through getenv ("Content-length"), The Web server sets this environment variable when it calls a CGI program that uses the Post method, and its text value represents the number of characters in the input that the Web server transmits to the CGI program. The example above shows how the CGI program interacts with the Web server.

CGI and fastcgi

How CGI works: Whenever a client requests a CGI, the Web server requests the operating system to generate a new CGI interpreter process (such as Php-cgi.exe), and a CGI process quits after processing one request, and then creates a new process when the next request comes. Of course, this can be done in cases where there is little or no concurrency in the traffic. But when traffic increases and concurrency exists, this is not the way to go. So there is the fastcgi.

FastCGI is like a resident (long-live) CGI, which can be executed all the time, so long as it is activated, it will not take a moment to fork once (this is the most notorious fork-and-execute mode of CGI).

  In general, the whole workflow of fastcgi is this:

Load the FASTCGI Process Manager (IIS ISAPI or Apache Module) at 1.Web server startup

2.fastcgi The Process manager itself, start multiple CGI interpreter processes (visible multiple php-cgi) and wait for a connection from the Web server.

3. When a client request arrives at Web server, the FASTCGI process manager selects and connects to a CGI interpreter. WEB server sends CGI environment variables and standard input to the FASTCGI child process php-cgi.

4. The FASTCGI child process returns standard output and error information from the same connection to the Web Server after processing is complete. When the fastcgi child process closes the connection, the request is processed to completion. The fastcgi child process then waits and processes the next connection from the FASTCGI process Manager (running in Web server). In CGI mode, php-cgi exits here.

php-fpm and spawn-fcgi

SPAWN-FCGI is a general-purpose fastcgi Management Server, which is part of LIGHTTPD, and many people use lighttpd spawn-fcgi for management in fastcgi mode. But there are shortcomings, so php-fpm is for PHP, a fastcgi implementation, he is responsible for managing a process pool to handle requests from the Web server. Currently, PHP-FPM is built into PHP.

Apache module mode

Remember once in XP configuration Apache + PHP, will be configured in Apache below paragraph:

LoadModule Php5_module C:/php/php5apache2_2.dll

When PHP needs to run under the Apache server, in general, it can be integrated in the form of modules, when the role of the module is to receive Apache sent over the php file request, and processing the requests, and then return the processed results to Apache. If we configure the PHP module in its configuration file before Apache starts, the PHP module registers the apache2 ap_hook_post_config hook and starts the module at Apache startup to accept requests for PHP files.

Apache hook mechanism refers to: Apache allows the module (including internal modules and external modules, such as mod_php5.so,mod_perl.so, etc.) to inject the custom function into the request processing loop. In other words, the module can join the Apache request processing process by hooking up its own processing function at any one of Apache's processing stages. Mod_php5.so/php5apache2.dll is the inclusion of the custom functions, through the hook mechanism into Apache, at all stages of the Apache processing process is responsible for processing PHP requests.

Someone tested NGINX+PHP-FPM may reach apache+mod_php5 5~10 times in high concurrency, and now nginx+php-fpm use people

In-depth understanding of PHP operating mode

Related Article

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.