In-depth understanding of several PHP operating modes

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

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 CodeThe code is 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 CodeThe code is 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 CodeThe code is as follows:
<directory/>
Options FollowSymLinks
AllowOverride None
Order Deny,allow
Deny from all
</Directory>

Switch
Copy CodeThe code is 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 CodeThe code is 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.

In-depth understanding of several PHP operating modes

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.