Home  >  Article  >  Backend Development  >  Detailed explanation of the four PHP running modes

Detailed explanation of the four PHP running modes

小云云
小云云Original
2018-05-12 11:26:415246browse

There are 4 PHP operating modes:

1) cgi Common Gateway Interface (Common Gateway Interface))

2) fast-cgi resident (long-live) type CGI php-fpm

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, it is a program. CGI is like a bridge that connects the web page and the execution program in the WEB server. 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 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 not found in the /cgi-bin/ directory php-cgi. You can cp one from the php 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.

question:

1) If the cgi program cannot be executed in /usr/local/httpd/cgi-bin/ and a 403 or 500 error is encountered

Open the apache error log and the following prompt will appear: 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 file What is the first sentence of the output? It should be similar to the following

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

or Content-type:text /html\n\n

Note: Two blank lines should be output after declaring Content-type.

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', filling 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, 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 type CGI 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). 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, starts multiple CGI interpreter processes (multiple php-cgi.exe visible in the task manager) and waits Connection from 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 or .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 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 The logical processing is separated from the server, and the heavy-load IO processing is still left to the host server, so that the host server can concentrate on IO. For an ordinary dynamic web page, the logical processing may only be a small part, and a large number of pictures and other static

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, edit top_dir = /usr/local/httpd

make

make install

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

After compiling like this, php-cgi in the PHP bin directory is the fastcgi mode php interpreter

After successful installation, execute

php -v Output

PHP 5.3.2 (cgi-fcgi).

The output here includes cgi-fcgi

Note:

1. Compilation parameters cannot be added –with-apxs=/usr/local/httpd/bin/apxs Otherwise, the installed PHP executable file is in cli mode

2 If you do not add --disable-cli when compiling, PHP 5.3.2 will be output ( cli)

3) Configure apache

Need to configure apache to run the php program in fastcgi mode

vi httpd.conf

How we use the virtual machine Implementation:

#Load fastcgi module

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>
 
或者
<IfModule mod_fastcgi>ScriptAlias /fcgi-bin/ "/usr/local/php/bin"
 #定义目录映射FastCgiServer /usr/local/php/bin/php-cgi   -processes 10 
 #配置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结尾的请求都要用php-fastcgi来处理Action php-fastcgi /fcgi-bin/php-cgi 
 #设置php-fastcgi的处理器
</IfModule>

4). Restart apache, check 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 whether /usr/local/httpd/fcgi-bin/ has sufficient permissions.

or

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>
改为:
<Directory />
    Options FollowSymLinks
    AllowOverride None
Order allow,deny
Allow from all
</Directory>

will do.

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 "php -m" under Linux 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

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

Module mode is integrated in the form of mod_php5 module, at this time mod_php5 The function of the module is to receive PHP file requests passed by Apache, process these 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 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 used with The web server is up and running together. (It is an extension of apache based on CGI to speed up the operating efficiency of PHP)

[plain]view plaincopyprint?

1 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.

Related recommendations:

Summary of PHP running modes

The above is the detailed content of Detailed explanation of the four PHP running modes. For more information, please follow other related articles on the PHP Chinese website!

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