Home  >  Article  >  Backend Development  >  In-depth understanding of PHP running mode_PHP tutorial

In-depth understanding of PHP running mode_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:09:42889browse

There are 4 operating modes for PHP:
1) cgi Common Gateway Interface)
2) fast-cgi resident (long- live) type CGI
3) cli command line operation (Command Line Interface)
4) web module mode (module mode run by web servers such as apache)
1 .CGI (Common Gateway Interface)
CGI is the Common Gateway Interface (Common Gateway Interface). It is a program. In layman's terms, CGI is like a bridge that connects the web page and the execution in the WEB server. The program is connected, it passes the instructions received by the HTML to the server's execution program, and then returns the results of the server's execution program to the HTML page. CGI is extremely cross-platform and can be implemented on almost any operating system. CGI is already an older model and has been rarely used in recent years.

Every time there is a user request, a cgi sub-process will be created first, then the request will be processed, and the sub-process will be terminated 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, CPU time, etc. will be occupied, resulting in low performance. Therefore, a server using CGI will have as many CGI sub-processes as there are connection requests. Repeated loading of sub-processes is the main reason for low CGI performance.
If you don’t want to embed PHP into server-side software (such as Apache) and install it as a module, you can choose to install it in CGI mode. Or use PHP with different CGI wrappers to create secure chroot and setuid environments for your code. In this way, each client requests a php file, and the web server calls php.exe (php.exe under win, php under Linux) to interpret the file, and then returns the result of the interpretation to the client in the form of a web page. This installation method usually installs the PHP executable file into the cgi-bin directory of the web server. CERT Recommendation CA-96.11 recommends not placing any interpreters in the cgi-bin directory.

The advantage of this method is that it separates the web server from specific program processing, has a clear structure and strong controllability. At the same time, the disadvantage is that if there is high access demand, the cgi process will fork. It becomes a huge burden on the server. Just imagine that hundreds of concurrent requests cause the server to fork hundreds of processes. This is why cgi has always been notorious for low performance and high resource consumption.

CGI mode installation:
CGI is an older mode and has rarely been used in recent years, so we are just for testing.
To install CGI mode, you need to comment out the line
LoadModule php5_module modules/libphp5.so. If you don't comment this line, it will go all the way to 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 download it from php yourself There is a cp in the bin.
Then restart apache, then open the test page and find that the Server API changes to: CGI/FastCGI. Description: Successfully switched to cgi mode.
Problems:
1) If the cgi program cannot be executed if it is placed in /usr/local/httpd/cgi-bin/ and encounters a 403 or 500 error
When opening the apache error log, the following prompt appears: Permission denied: exec of
You can check the attributes of the cgi program. According to the definition in the Linux contexts file, /usr/local/httpd/cgi-bin/ must be the httpd_sys_script_exec_t attribute. Check it with 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 cgi in the virtual host, refer to question 2 to make it use normal functions. After that, set the context of the cgi file to
httpd_sys_script_exec_t through chcon. chcon -R -t httpd_sys_script_exec_t cgi-bin/
2) apache error message: .... malformed header from script. Bad header=
According to the prompt, there is a problem with the header. Check the first sentence of the file output. What it is, it should be similar to the following
Content-type: text/plain; charset=iso-8859-1nn
or Content-type: text/htmlnn
Note: After declaring Content-type, two outputs are required. A blank line.
3) Apache error message: Exec format error
Script interpreter setting error. 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, there is no need to fill in 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 that can be executed all the time As long as it is activated, it will not take time to fork every time (this is the most criticized fork-and-execute mode of CGI).
The working principle of FastCGI is:
(1). When the Web Server starts, the FastCGI process manager is loaded [PHP’s FastCGI process manager is 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 visible in the task manager) and waits for the connection from the Web Server.
(3). When the client request reaches 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 subprocess php-cgi.
(4). After the FastCGI sub-process completes processing, it returns standard output and error information to the Web Server from the same connection. When the FastCGI child process closes the connection, the request is processed. The FastCGI child process then waits for and handles the next connection from the FastCGI process manager (running in WebServer). In normal CGI mode, php-cgi.exe exits here.
In CGI mode, you can imagine how slow CGI usually is. Every web request to PHP must re-parse php.ini, reload all dll extensions and re-initialize all data structures. With FastCGI, all of this happens only once, when the process starts. An added bonus is that persistent database connections work.
Advantages of Fastcgi:
1) From a stability point of view, fastcgi runs cgi in an independent process pool. If a single process dies, the system will be very unstable. Easily discard it and then reassign a new process to run the logic.
2) From a security point of view, Fastcgi supports distributed computing. Fastcgi is completely independent from the host server. No matter how fastcgi is down, it will not bring down the server.
3) From a performance point of view, fastcgi separates the processing of dynamic logic from the server. The heavy-load IO processing is still left to the host server, so that the host server can focus on IO. For an ordinary dynamic web page, There may only be a small part of the logical processing, and a large number of static pictures etc.
FastCGI Disadvantages: After talking about the advantages, let’s talk about the disadvantages. From my actual use, FastCGI mode is more suitable for servers in production environments. But it is not suitable for development machines. Because when using Zend Studio to debug the program, FastCGI will think that the PHP process has timed out and return a 500 error on the page. This was so annoying that I switched back to ISAPI mode on my development machine.
Install fastcgi mode:
The path to install apache is /usr/local/httpd/
The path to install php 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,
There is one more file in /usr/local/httpd/modules/: mod_fcgid.so
2) Recompile php
./configure --prefix=/usr/local/php --enable -fastcgi --enable-force-cgi-redirect --disable-cli
make
make install
After compiling in this way, php-cgi in the PHP bin directory will be the fastcgi mode php interpreter
After successful installation, execute
php -v to output
PHP 5.3.2 (cgi-fcgi).
The output here includes cgi-fcgi
Note:
1. The compilation parameters cannot be added –with-apxs=/usr/local/httpd/bin/apxs, otherwise the installed php execution file is in cli mode
2 If you do not add - -disable-cli outputs PHP 5.3.2 (cli)

3) Configure apache
You need to configure apache to run the php program in fastcgi mode
vi httpd.conf
We use a virtual machine Implemented by:

Copy code The code is as follows:

#Load fastcgi module
LoadModule fastcgi_module modules/mod_fastcgi.so
#//Execute fastcgi in static mode and start 10 processes
FastCgiServer /usr/local/php/bin/php-cgi -processes 10 -idle-timeout 150 -pass-header HTTP_AUTHORIZATION

#
DocumentRoot /usr/local/httpd/fcgi-bin
ServerName www.fastcgitest.com

ScriptAlias ​​/fcgi-bin/ / usr/local/php/bin/ #Define directory mapping/fcgi-bin/ instead of /usr/local/php/bin/
Options +ExecCGI
AddHandler fastcgi-script .php .fcgi #Requests ending in .php All must be handled with php-fastcgi
AddType application/x-httpd-php .php #Add MIME type
Action application/x-httpd-php /fcgi-bin/php-cgi #Set up php-fastcgi Processor: /usr/local/php/bin/php-cgi

Options Indexes ExecCGI
Order allow,deny
allow from all



or
Copy code code As follows:

ScriptAlias ​​/fcgi-bin/ "/usr/local/php/bin" #Define directory mapping FastCgiServer /usr/local/php/bin/php-cgi -processes 10 #Configure fastcgi server,SetHandler fastcgi-scriptOptions FollowSymLinksOrder allow,denyAllow from allAddType application/x-httpd-php .php #Add MIME type AddHandler php -fastcgi .php #Requests ending in .php must be processed with php-fastcgi Action php-fastcgi /fcgi-bin/php-cgi #Set the processor of php-fastcgi


4). Restart apache and check phpinfo. If the server information is:
Apache/2.2.11 (Unix) mod_fastcgi/2.4.6 or the like, it means the installation is successful.
If a 403 error occurs, check whether /usr/local/httpd/fcgi-bin/ has sufficient permissions.
or
Copy code The code is as follows:


Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all


Changed to:
Copy code The code is as follows:


Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
< ;/Directory>

is fine.
ps -ef|grep php-cgi can see 10 fastcgi processes running.
3. CLI mode
cli is the command line running mode of php. You often use it, but you may not notice it (for example: we are under linux Often use "php -m" to find out which extensions PHP has installed, which is the PHP command line running mode; interested students can enter php -h to study the running mode in depth)
1. Let PHP run the specified file.
php script.php
php -f script.php
The above two methods (with or without the -f parameter) can run the script's script.php. You can choose any file to run. The PHP scripts you specify do not have to have a .php extension; they can have any file name and extension.
2. Run PHP code directly on the command line.
php -r "print_r(get_defined_constants());"
When using this method, please pay attention to the substitution of shell variables and the use of quotation marks.
Note: Please read the above example carefully, there are no start and end markers when running the code! With the -r parameter, these markers are unnecessary and will cause a syntax error.
3. Provide the PHP code that needs to be run through standard input (stdin).
The above usage provides us with very powerful functions, allowing us to dynamically generate PHP code and run these codes through the command line as shown in the following example:
$ some_application | some_filter | php | sort - u >final_output.txt
4. Module mode
Module mode is integrated in the form of mod_php5 module. At this time, the function of mod_php5 module is to receive the data passed by Apache. PHP file requests, processes these requests, and returns 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 ap_hook_post_config hook of apache2 and starts this module when Apache starts to accept requests for PHP files.

In addition to this loading method at startup, Apache's modules can be dynamically loaded at runtime, which means that the server can be expanded without the need to recompile the source code, or even without stopping at all. server. All we need to do is to send the signal HUP or AP_SIG_GRACEFUL to the server to notify the server to reload the module. But before dynamic loading, we need to compile the module into a dynamic link library. Dynamic loading at this time is to load the dynamic link library. The processing of dynamic link libraries in Apache is completed through the module mod_so, so the mod_so module cannot be dynamically loaded, it can only be statically compiled into the core of Apache. This means it is started along with Apache.
How does Apache load modules? Let’s take the mod_php5 module mentioned earlier as an example. First we need to add a line to Apache's configuration file httpd.conf:
This operating mode is what we often used when using the apache server in the windows environment. In modularization (DLL), PHP is together with the web server. up and running. (It is an extension of apache based on CGI to speed up the operating efficiency of PHP)
Copy the code The 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 source code of the module implementation. The second option is the path where the module is located. If you need to load a module while the server is running, you can send the signal HUP or AP_SIG_GRACEFUL 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)
There are two common stacks using FastCGI: lighthttpd+spawn- fcgi; the other is nginx+PHP-FPM (spawn-fcgi can also be used).
A. As mentioned above, both structures use FastCGI to support PHP, so HTTPServer is completely liberated and can respond better and handle concurrently. Therefore, both lighttpd and nginx have the reputation of being small, but powerful and efficient.
B. The two can be divided into good and bad. Since spawn-fcgi is part of lighttpd, if lighttpd is installed, spawn-fcgi will generally be used to support PHP. However, some users currently say that lighttpd’s spwan- When fcgi has high concurrent access, the memory leak mentioned above will occur and even fastcgi will automatically restart. That is: the PHP script processor crashes. If the user accesses it at this time, a white page may appear (that is, PHP cannot be parsed or an error occurs).

Another: First of all, nginx does not include fastcgi (spawn-fcgi) like lighttpd itself, so it is completely lightweight and must use a third-party FastCGI processor to parse PHP, so In fact, it seems that nginx is very flexible. It can connect to any third-party parsing processor to realize the parsing of PHP (it is easy to set up in nginx.conf). nginx can use spwan-fcgi (lighttpd needs to be installed together, but the port needs to be avoided for nginx. Some older blogs have installation tutorials in this regard). However, since spawn-fcgi has the defects gradually discovered by users as mentioned above, now Slowly reduce the use of nginx+spawn-fcgi combination.

C. Due to the defects of spawn-fcgi, a new third-party (currently still, I heard that they are working hard to add it to PHP core in the near future) FastCGI processor for PHP has appeared, called PHP-FPM ( You can google for details). Compared with spawn-fcgi, it has the following advantages:
Since it is developed as a PHP patch, it needs to be compiled together with the PHP source code during installation, which means that it is compiled into PHP core, so in terms of performance It is better;
At the same time, it is better than spawn-fcgi in handling high concurrency, at least it will not automatically restart the fastcgi processor. The specific algorithms and designs used can be found on Google.

Therefore, as mentioned above, due to the lightweight and flexibility of nginx, its current performance is superior, and more and more people are gradually using this combination: nginx+PHP/PHP-FPM
6. Summary
At present, there are basically three popular stacks in the
HTTPServer area:
(1) Apache+mod_php5
(2) lighttp +spawn-fcgi
(3) nginx+PHP-FPM
The performance of the latter two of the three may be slightly better, but Apache is still the leader due to its rich modules and functions. Some people have tested that nginx+PHP-FPM may reach 5 to 10 times that of Apache+mod_php5 under high concurrency conditions. Now more and more people are using nginx+PHP-FPM.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327261.htmlTechArticlePHP has 4 operating modes: 1) cgi Common Gateway Interface) 2) fast-cgi Long-live CGI 3) cli command line operation (Command Line Interface)...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn