PHP run mode (CGI,FAST-CGI,CLI, ISAPI, Web module mode) "Reprint"

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

PHP operating mode has 5 minutes:

1) CGI Universal Gateway Interface (Common Gateway Interface))
2) fast-cgi resident (long-live) type CGI
3) CLI command line run (Interface)
4) ISAPI mode (used in Windows)
5) 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.

Problem:

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 in 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 : To say the benefits, but also to say the 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.

Install fastcgi mode: Install Apache path is/usr/local/httpd/install PHP path is/usr/local/php/ 1) Install mod_fastcgiwget Http://www.fastcgi.com/dist/mod_fastcgi-2.4.6.tar.gztar zxvf MOD_FASTCGI-2.4.6.TAR.GZCD MOD_FASTCGI-2.4.6CP Makefile.ap2 Makefilevi Makefile, edit top_dir =/usr/local/httpdmakemake Install after installation,/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-climake make install so after compiling , in the bin directory of PHP php-cgi is the fastcgi mode PHP interpreter installed successfully after the execution of php-v output PHP 5.3.2 (cgi-fcgi). Here the output takes the cgi-fcgi Note: 1. Compile parameter cannot add –WITH-APXS=/USR/LOCAL/HTTPD/BIN/APXS otherwise installed PHP execution file is CLI mode 2 if compile without--disable-cli then output PHP 5.3.2 (CLI) 3) Configure ApacheNeed to configure Apache to run PHP program in fastcgi mode VI httpd.conf We use virtual machines to implement:  #加载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 /replace  /usr/local/php/bin/     options +execcgi     addhandler fastcgi-script. php. fcgi         #.php end of request will be handled with php-fastcgi       addtype application/ x-httpd-php. php      #增加MIME类型      action application/x-httpd-php/fcgi-bin/php-cgi   #设置php-fastcgi 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 <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&nbsp; #增加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,Check Phpinfo If the server information is: apache/2.2.11 (Unix) mod_fastcgi/2.4.6 and so on, the installation is successful. If a 403 error occurs, check to see if the/usr/local/httpd/fcgi-bin/has sufficient permissions. or <directory/> Options followsymlinks allowoverride None Order deny,allow deny from ALL&LT;/DIRECTORY&G t; change to: <directory/> Options followsymlinks allowoverride noneorder allow,denyallow from all</directory> to the. 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. ISAPI Run mode

ISAPI, the Internet Server application Program Interface, is a set of Internet service-oriented API interfaces provided by Microsoft, an ISAPI DLL that can be long-standing in memory after being activated by a user request. Waiting for another user request, you can also set up a DLL in a number of user request handler functions, in addition, the ISAPI DLL application and the WWW server in the same process, the efficiency is significantly higher than the CGI. (due to the exclusivity of Microsoft, only running in the Windows environment)

5. 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)
    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 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.

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

7. 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. http://blog.csdn.net/hguisu/article/details/7386882

PHP run mode (CGI,FAST-CGI,CLI, ISAPI, Web module mode) "Reprint"

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.