search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the four PHP running modes

Detailed explanation of the four PHP running modes

May 12, 2018 am 11:26 AM
phpmodelDetailed explanation

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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment