Home > Backend Development > PHP Tutorial > Summary of PHP running modes

Summary of PHP running modes

高洛峰
Release: 2023-03-04 10:02:01
Original
1745 people have browsed it

PHP has 4 operating modes:

1) cgi Common Gateway Interface)
2) fast-cgi long-live CGI
3) cli command line operation (Command Line Interface)
4) web module mode (module mode for running web servers such as apache)
5) ISAPI (Internet Server Application Program Interface)

Note: After PHP5.3, PHP no longer has ISAPI mode, and there is no longer the php5isapi.dll file after installation. To use a higher version of PHP on IIS6, you must install the FastCGI extension and then enable IIS6 to support FastCGI.

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 web pages and WEB The execution program in the server is connected, it passes the instructions received by 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 rarely been 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 to 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 the 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 already 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 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.
                                                                                                              *& : Permission denied: exec of

can check the attributes of the cgi program. As defined 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 file output What is the first sentence? It should be similar to the following

Content-type: text/plain; charset=iso-8859-1nn

Or Content-type: text/htmlnn
Note: Declare Content-type well Two blank lines should be output at the end.

3) Apache error message: Exec format error
Script interpreter setting error. The first line of the script should fill in the path of the script interpreter in the form of '#!Interpreter Path'. If it is a PERL program, the common path is: #!/usr/bin/perl or #!/usr/local/bin /perl If it is a PHP program, you do not 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. It can be executed all the time. After activation, 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), the FastCGI process manager is loaded when the Web Server starts [PHP’s FastCGI process manager is PHP-FPM (php-FastCGI Process Manager)] (IIS ISAPI or Apache Module);

(2), FastCGI process manager initializes itself and starts multiple CGI interpreter processes (multiple php- can be seen in the task manager) cgi.exe) and wait 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 the perspective of stability, fastcgi runs cgi in an independent process pool. If a single process dies, the system can be very stable. 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, and fastcgi will not bring down the server no matter how down it is.
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 installation path of apache is /usr/local/httpd/
The installation path of 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,编辑top_dir = /usr/local/httpd
make
make insta
Copy after login

After installation, there will be 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
Copy after login

After compiling in this way, php-cgi in the PHP bin directory It is the fastcgi mode php interpreter
After successful installation, execute

php -v 输出
PHP 5.3.2 (cgi-fcgi).
Copy after login

The output here contains cgi-fcgi

Note:

1. Do not add –with-apxs=/usr/local/httpd/bin/apxs to the compilation parameters, otherwise the installed php execution file will be in cli mode
2 If compiled If –disable-cli is not added, PHP 5.3.2(cli)
3) Configure apache

Need to configure apache to run the php program in fastcgi mode
vi httpd.conf

We use a virtual machine to implement:

#加载fastcgi模块
LoadModule fastcgi_module   modules/mod_fastcgi.so
#//以静态方式执行fastcgi 启动了10进程
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/ 代替 /usr/local/php/bin/
   Options +ExecCGI
   AddHandler fastcgi-script .php .fcgi     #.php结尾的请求都要用php-fastcgi来处理
   AddType application/x-httpd-php .php   #增加MIME类型
   Action application/x-httpd-php /fcgi-bin/php-cgi #设置php-fastcgi的处理器: /usr/local/php/bin/php-cgi
 <Directory /usr/local/httpd/fcgi-bin/>
   Options Indexes ExecCGI
   Order allow,deny
   allow from all
 </Directory>
</VirtualHost>
Copy after login

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

<Directory />
  Options FollowSymLinks
  AllowOverride None
  Order deny,allow
  Deny from all
</Directory>
Copy after login

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 often use it under Linux) php -m "Find those extensions installed by PHP, 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
Copy after login

Both of the above 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

The module mode is integrated in the form of mod_php5 module. At this time, the role of mod_php5 module It receives PHP file requests passed by Apache, processes these requests, and then 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 having to recompile the source code, or even at all. No need to stop the 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 the Apache configuration file httpd.conf:

This operating mode is what we often used when using the apache server in the windows environment, and in modularization (DLL), PHP is up and running together with the web server. (It is an extension of apache based on CGI to speed up the operating efficiency of PHP)

LoadModule php5_module modules/mod_php5.so

Here we use LoadModule command. The first parameter of this 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 ISAPI mode

ISAPI (Internet Server Application Program Interface) is a set of API interfaces for Internet services provided by Microsoft. An ISAPI DLL can be activated at the request of the user. Afterwards, it resides in memory and waits for another request from the user. You can also set multiple user request processing functions in one DLL. In addition, the ISAPI DLL application and the WWW server are in the same process, and the efficiency is significantly higher than that of CGI. (Due to Microsoft's exclusivity, it can only run in the Windows environment)

PHP is an Apache module. After the system is started, the Apache server pre-generates multiple process copies to reside in the memory. Once a request occurs, it will be processed immediately. Use these spare sub-processes for processing, so there is no delay caused by spawning sub-processes. These server copies do not exit immediately after processing an HTTP request, but stay in the computer waiting for the next request. The response to client browser requests is faster and the performance is higher.

6. 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 ones. 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 one: First of all, nginx does not include fastcgi (spawn-fcgi) like lighttpd itself, so it is completely lightweight. It must use a third-party FastCGI processor to parse PHP, so in fact, it looks like this nginx is very flexible. It can be connected to any third-party parsing processor to realize PHP parsing (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 tutorials on this installation), but because 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, there is now 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, called PHP -FPM (you can google it 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

7. Summary

At present, we can basically see that there are three popular stacks in

HTTPServer:

(1) Apache+mod_php5
( 2) lighttp+spawn-fcgi
(3) nginx+PHP-FPM

The performance of the last two of the three may be slightly better, but Apache has rich modules and functions. At present, Still the boss. 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.

For more articles related to PHP operating mode summary, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template