This article provides a detailed analysis of the PHP running mode. For more information, see
PHP running mode has four minutes: 1) cgi Common Gateway Interface ))
2) fast-cgi resident (long-live) type CGI
3) cli Command Line Interface)
4) web module mode (module mode for running apache and other web servers)
1. CGI (Common Gateway Interface) CGI is a Common Gateway Interface. it is a program. Generally speaking, CGI is like a bridge that connects the webpage to the execution program on the WEB server, it passes the commands received by HTML to the execution program on the server, and then returns the results of the execution program on the server to the HTML page. CGI provides excellent cross-platform performance and can be implemented on almost any operating system. CGI is already a relatively old model, which has been rarely used in recent years.
Each user request creates a cgi sub-process, processes the request, and ends the sub-process after processing. this is the fork-and-execute mode. When the number of user requests is very large, a large amount of system resources such as memory and CPU time will be squeezed out, resulting in low efficiency. As a result, the number of connection requests to servers in the cgi mode is limited to the number of cgi sub-processes. repeated loading of sub-processes is the main cause of low cgi performance.
If you do not want to embed PHP into the server software (such as Apache) as a module for installation, you can choose to install it in CGI mode. Or use PHP to encapsulate different CGI to create a safe chroot and setuid environment for the code. In this case, each client requests a php file, and the webserver calls php.exe(win.exe php.exe, linux is php) to explain the file, and then returns the result of the explanation to the client in the form of a webpage. This installation method usually installs PHP executable files to the cgi-bin directory of the web server. The CERT proposal CA-96.11 recommends that you do not place any interpreter in the cgi-bin directory.
The advantage of this method is that the web server is independent from the specific program, with a clear structure and strong controllability. The disadvantage is that if the high access requirements are met, the cgi process fork will become a huge burden on the server, just like several hundred concurrent requests that cause the Server fork to generate hundreds of processes. This is also the reason why cgi has always suffered from poor performance and high resource consumption.
CGI mode installation: CGI is already an old mode, and it has been rarely used in recent years, so we just want to test it.
Comment out the installation of CGI mode
LoadModule php5_module modules/libphp5.so. If you do not comment this line, it will always go to the handler mode. That is, the module mode.
Then add action in httpd. conf:
Action application/x-httpd-php/cgi-bin/
If you cannot find php-cgi in the/cgi-bin/directory, you can use cp in the php bin.
Restart apache, open the test page, and find that the Server API becomes CGI/FastCGI. It indicates that the cgi mode is successfully switched.
Problem: 1) If the cgi program cannot be executed in/usr/local/httpd/cgi-bin/, if the program encounters a 403 or 500 error
The following error message is displayed when an apache error log is opened: Permission denied: exec
Check the cgi program attributes. as defined in the Linux contexts file, the/usr/local/httpd/cgi-bin/must be the httpd_sys_script_exec_t attribute. Run the command chcon-t httpd_sys_script_exec_t/var/www/cgi-bin /*. if cgi is cgi in the VM, refer to question 2 to enable normal use of common functions, and then set the context of the cgi file
Httpd_sys_script_exec_t. Chcon-R-t httpd_sys_script_exec_t cgi-bin/
2) apache error prompt:... malformed header from script. Bad header =
According to the prompts, there is a problem with the header. check the first sentence of the file output, which should be similar to the following:
Content-type: text/plain; charset = ISO-8859-1 \ n
Or Content-type: text/html \ n
Note: After the Content-type is declared, two empty rows are output.
3) apache error prompt: Exec format error
The script interpreter is set incorrectly. The first line of the script should start '#! In the form of interpreter path, enter 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 and you do not need to enter the interpreter path, the system will automatically find PHP.
2. Fastcgi mode Fast-cgi is an upgraded version of cgi. FastCGI is like a long-live CGI. it can be executed all the time, it will not take time to fork every time (this is the most criticized fork-and-execute mode for CGI ).
FastCGI works as follows:
(1) load FastCGI Process Manager when Web Server is started [PHP FastCGI Process Manager is a PHP-FPM (php-FastCGI Process Manager)] (iis isapi or Apache Module );
(2) FastCGI Process Manager initializes itself, starts multiple CGI interpreter processes (multiple php-cgi.exe in the Task Manager), and waits for a connection from the Web Server.
(3) when the client request arrives at the Web Server, the FastCGI process manager selects and connects to a CGI interpreter. The Web server sends CGI environment variables and standard input to the FastCGI sub-process php-cgi.
(4) after the FastCGI sub-process completes processing, the standard output and error messages are returned from the same connection to the Web Server. When the FastCGI sub-process closes the connection, the request processing is complete. The FastCGI sub-process then waits for and processes the next connection from the FastCGI Process Manager (running in WebServer. In the normal cgimode, php-cgi.exe exits.
In CGI mode, you can imagine how slow CGI is. Every Web request PHP must re-parse php. ini, re-load all dll extensions, and initialize all data structures. With FastCGI, all of these occur only once when the process starts. An additional benefit is that Persistent database connection can work.
Advantages of Fastcgi: 1) in terms of stability, fastcgi uses an independent process pool to run cgi. when a single process dies, the system can easily discard it and re-allocate the new process to run the logic.
2) in terms of security, Fastcgi supports distributed computation. fastcgi is completely independent from the host's server, and fastcgi does not bring down the server.
3) in terms of performance, fastcgi separates the processing of dynamic logic from the server, and leaves the high-load IO processing to the host server. in this way, the host server can concentrate on IO, for a common dynamic web page, logical processing may only have a small part, a large number of images and other static
FastCGI disadvantages: disadvantages are also described after the benefits are completed. In my practical use, FastCGI is more suitable for servers in the production environment. But it is not suitable for development machines. When Zend Studio is used to debug a program, FastCGI considers that the PHP process times out and returns error 500 on the page. This is annoying, so I switched back to the ISAPI mode on the development machine.
Install fastcgi mode: The path to install apache is/usr/local/httpd/
The php installation 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
After installation,
/Usr/local/httpd/modules/add 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 compilation, the PHP-cgi in the php bin directory is the php interpreter in fastcgi mode.
After the installation is successful, run
Php-v output
PHP 5.3.2 (cgi-fcgi ).
Cgi-fcgi is output here.
Note: 1. you cannot add-with-apxs =/usr/local/httpd/bin/apxs to the compilation parameters. Otherwise, the installed php execution file is in cli mode.
2. if -- disable-cli is not added during compilation, PHP 5.3.2 (cli) is output)
3) configure apache
You need to configure apache to run the php program in fastcgi mode.
Vi httpd. conf
We use virtual machines:
The code is as follows:
# Load fastcgi module LoadModule fastcgi_module modules/mod_fastcgi.so
# // Execute fastcgi in static mode to start 10 processes
FastCgiServer/usr/local/php/bin/php-cgi-processes 10-idle-timeout 150-pass-header HTTP_AUTHORIZATION
ScriptAlias/fcgi-bin // usr/local/php/bin/# define directory ing/fcgi-bin/replace/usr/local/php/bin/
Options + ExecCGI
AddHandler fastcgi-script. php. fcgi #. php requests end with php-fastcgi.
AddType application/x-httpd-php. php # add the MIME type
Action application/x-httpd-php/fcgi-bin/php-cgi # set the php-fastcgi processor:/usr/local/php/bin/php-cgi
Options Indexes ExecCGI
Order allow, deny
Allow from all
Or
The code is as follows:
ScriptAlias/fcgi-bin/"/usr/local/php/bin" # define directory ing FastCgiServer/usr/local/php/bin/php-cgi-processes 10 # configure fastcgi server, SetHandler fastcgi-scriptOptions FollowSymLinksOrder allow, denyAllow from all AddType application/x-httpd-php. php # add the MIME type AddHandler php-fastcgi. php #. php-fastcgi must be used to process php-fastcgi/fcgi-bin/php-cgi # set the php-fastcgi processor.
4) in apache under restart, view phpinfo. if the server information is:
Apache/2.2.11 (Unix) mod_fastcgi/2.4.6 indicates that the installation is successful.
If error 403 occurs, check whether/usr/local/httpd/fcgi-bin/has sufficient permissions.
Or
The code is as follows:
Options FollowSymLinks
AllowOverride None
Order deny, allow
Deny from all
Changed:
The code is as follows:
Options FollowSymLinks
AllowOverride None
Order allow, deny
Allow from all
You can.
Ps-ef | grep php-cgi: 10 fastcgi processes are running.
3. CLI mode Cli is the command line running mode of php. it is often used, but it may not be noticed (for example: in linux, we often use "php-m" to find out which extensions are installed in PHP, that is, the PHP command line running mode. if you are interested, you can enter php-h to study the running mode in depth)
1. run the specified file in PHP.
Php script. php
Php-f script. php
The above two methods (using or without the-f parameter) can run script. php of the script. You can select any file to run the script. the PHP script you specified does not have to use. php as the extension. they can have any file name and extension.
2. run the PHP code directly on the command line.
Php-r "print_r (get_defined_constants ());"
When using this method, pay attention to the substitution of shell variables and the use of quotation marks.
Note: read the preceding example carefully. there is no start or end mark when running the code! After the-r parameter is added, these tokens are not required, and adding them will lead to syntax errors.
3. provide the PHP code to be run through standard input (stdin.
The above usage provides us with very powerful functions, so that we can dynamically generate PHP code and run the code through the command line as follows:
$ Some_application | some_filter | php | sort-u> final_output.txt
4. module mode The module mode is integrated in the form of the mod_php5 module. in this case, the mod_php5 module is used to receive php file requests passed by Apache, process these requests, and then return the processed results to Apache. If the PHP module (mod_php5) is configured in the configuration file before Apache is started, the PHP module registers the ap_hook_post_config hook of apache2, start this module when Apache starts to accept requests from the PHP file.
In addition to this loading method at startup, Apache modules can be dynamically loaded during running, which means that the server can be extended without re-compiling the source code, you do not even need to stop the server. All we need to do is send a signal HUP or AP_SIG_GRACEFUL to the server to notify the server to reload the module. However, before dynamic loading, we need to compile the module into a dynamic link library. In this case, dynamic loading is to load the dynamic link library. In Apache, the processing of the dynamic link library is done through the module mod_so. Therefore, the mod_so module cannot be dynamically loaded and can only be statically compiled into the Apache core. This means that it is started with Apache.
How does Apache load modules? The mod_php5 module we mentioned previously is used as an example. First, add a line in the configuration file httpd. conf of Apache:
This running mode is often used by apache servers in windows. in modularization (DLL), PHP is started and run together with the Web server. (It is an extension of apache based on CGI to speed up the running efficiency of PHP)
The code is as follows:
LoadModule php5_module modules/mod_php5.so
Here we use the LoadModule command. The first parameter of this command is the module name, which can be found in the module implementation source code. The second option is the path of the module. If you need to load the module when the server is running, you can send the HUP or AP_SIG_GRACEFUL signal to the server. Once the signal is received, Apache will reload the module without restarting the server.
5. php running mode in Nginx (Nginx + PHP-FPM) The FastCGI method is commonly used in two types of stack: ligthttpd + spawn-fcgi; the other is nginx + PHP-FPM (spawn-fcgi can also be used ).
A. As mentioned above, both of these structures use FastCGI to support PHP. Therefore, HTTPServer is completely released to better respond to and concurrently process requests. Therefore, both lighttpd and nginx have the reputation of small, but powerful and efficient.
B. The two can also be classified into good or bad ones. since spawn-fcgi is a part of lighttpd, lighttpd is installed with spawn-fcgi to support php, however, some users say that when the spwan-fcgi of ligttpd is accessed in high concurrency, the memory leakage mentioned above may even automatically restart fastcgi. That is, if the PHP script processor is on the machine and the user accesses it at this time, there may be white pages (that is, PHP cannot be parsed or error ).
Another: nginx does not have lighttpd including fastcgi (spawn-fcgi). Therefore, it is completely lightweight and can be parsed using a third-party FastCGI processor, as a result, nginx is very flexible. it can be connected to any third-party processor for parsing to achieve PHP parsing (in nginx. conf ). Nginx can use spwan-fcgi (lighttpd needs to be installed together, but the Port needs to be avoided for nginx. some earlier blogs have Installation Tutorials in this regard ), but since spawn-fcgi has the defects gradually discovered by users described above, it is now slowly reducing the use of nginx + spawn-fcgi combinations.
C. Due to spawn-fcgi defects, a new third-party PHP FastCGI processor (which is still working hard to join PHP core in the near future) has emerged, is called PHP-FPM (can google ). Compared with spawn-fcgi, it has the following advantages:
Because it is developed as a PHP patch, it needs to be compiled together with the php source code during installation, that is, compiled into the php core, so it should be better in terms of performance;
At the same time, it is superior to spawn-fcgi in terms of processing high concurrency, at least it will not automatically restart the fastcgi processor. Google can understand the specific algorithms and designs used.
Therefore, as mentioned above, nginx is simple and flexible, so the current performance is superior, more and more people gradually use this combination: nginx + PHP/PHP-FPM
6. Summary Currently
HTTPServer can be seen in three types of stacks:
(1) Apache + mod_php5
(2) lighttp + spawn-fcgi
(3) nginx + PHP-FPM
The performance may be slightly better between the two, but Apache is still the boss because of its rich modules and functions. Some people test nginx + PHP-FPM in high concurrency may reach Apache + mod_php5 5 ~ 10 times, now more and more people use nginx + PHP-FPM.
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.