PHP face question five How to invoke PHP and PHP-FPM function and how it works

Source: Internet
Author: User
Tags nginx server

This article is about the PHP surface question five how nginx call PHP and PHP-FPM function and work principle, have a certain reference value, now share to everyone, have the need of friends can refer to

Nginx How to invoke PHP


The use of nginx+php as an architectural model of webserver is widely used today. The first step, however, is to get Nginx to invoke PHP correctly. Because Nginx calls PHP is not as straightforward as calling a static file, it is necessary to execute PHP scripts dynamically. So it involves the configuration of the nginx.conf file. This step for beginners generally need online search information, for the general skilled, there are a lot of students do not understand why this configuration. The main content of this paper is how to correctly configure the PHP calling method and the basic principle of configuration in Nginx server.

First, nginx+php operating principle:

First of all, a simple theory, the current mainstream nginx+php operating principle is as follows:
1, Nginx worker process directly manages each request to Nginx network request.
2. For PHP, because PHP is the role of a CGI program throughout the network request, the process manager named PHP-FPM is used to manage these requested PHP programs. The PHP-FPM program, like Nginx, requires a listening port and a master and worker process. The worker process manages each PHP process directly.
3. About FASTCGI:FASTCGI is a process manager that manages the CGI process. There are many process managers on the market that implement the FASTCGI function, and PHP-FPM is one of them. Another point, php-fpm as a fast-cgi process Management service, will listen to the port, the general default listening to 9000 port, and is listening to the local, that is, only receive port requests from the local, so we usually enter the command Netstat-nlpt|grep PHP-FPM Will get:

TCP        0      0 127.0.0.1:9000              0.0.0.0:*                   LISTEN      1057/php-fpm

The 127.0.0.1:9000 here is the meaning of listening to the native 9000 port.
4, about the fastcgi configuration file, the current fastcgi configuration file is generally placed in the nginx.conf sibling directory, configuration file form, generally there are two kinds:

Fastcgi.conf  and Fastcgi_params. Different nginx versions will have different configuration files, and there is a very important difference between the two profiles: The following configuration is missing from the fastcgi_parames. Fastcgi_param  script_filename    $document _root$fastcgi_script_name;

We can either open the file with the fastcgi_params above line or add it dynamically where you want to use the configuration. Make the configuration effective.
5, when the need to deal with PHP requests, Nginx worker process will transfer the request to the PHP-FPM worker process to handle, that is, the first call of the Nginx PHP, in fact, strictly speaking is nginx indirectly call PHP.
Knowing the five simple principles above, it is easy to configure the PHP calling method in Nginx.

Second, the configuration file:

Put the code directly on the line to explain, here to post a normal startup PHP script of the simplest nginx vhost configuration:

server {listen 8011;      server_name test.cn; Location ~ \.php?.          *$ {root/share/test;          Fastcgi_pass 127.0.0.1:9000;          Fastcgi_param script_filename $document _root$fastcgi_script_name;      Include Fastcgi_params; }  }

1, the first curly brace server{}: Needless to say, to represent a separate server,
2, listen 8011: On behalf of the server listening 8011 port
3, Location ~ php?. *${}: Represents a location that matches the corresponding URI, matches a class of URIs, and makes custom logic and configuration for matching URI requests. The location here matches all of the. PHP URI requests, such as: HTTP://192.168.244.128:8011/TEST.PHP/ASDASD http://192.168.244.128:8011/index.php, etc.
4, Root/share/test: request the resource root directory, tell the URI matching to the location under the/share/teset folder down to find the same name resources.
5, Fastcgi_pass 127.0.0.1:9000: This line begins to be the focus of this article: This line of code means that the URI request that enters into the location is a CGI program and sends the request to port 9000, which is referred to php-fpm for processing.
6, Fastcgi_param Script_filename

Fastcgi_script_name; : This line of configuration means: Dynamically added a line fastcgi configuration, configuration content is script_filename, inform the management process, CGI script name. Because my nginx only fastcgi_params files, there is no fastcgi.conf file, so to make php-fpm know the specific value of script_filename, it is necessary to dynamically add this line configuration.
7, include Fastcgi_params; Introducing the FASTCGI configuration file
The above is the simplest version of the Nginx startup PHP script is the simplest configuration, after restarting Nginx, in the/share/test directory to create a xx.php file, enter


Three, Summary:

In fact, to call PHP such a CGI script, as long as the understanding of the 5-point principle I mentioned at the beginning, and then combined with 5-7-line configuration explained, it is clear why this configuration is needed. For the novice, is often fastcgi,php-fpm CGI program to get confused, random configuration has been, run the line, also do not go into its principle. So what I hope to write here can bring a little help to the reader.

How the PHP-FPM works

First, agent and reverse proxy
Real-life examples
1. Forward proxy: Access to google.com

For example, because Google is a wall, we need a VPN over the wall to access the google.com.

VPN for "We", is perceptible (we connect VPN) VPN for "Google Server", is not aware of (Google only know that there are HTTP requests come over).

For a person to perceive, but the server does not perceive the server, we call him forward to the proxy server.

2. Reverse proxy: Load balancing via reverse proxy

For example, when we visit Baidu.com, Baidu has a proxy server, which can be load balanced and routed to a different server through this proxy server. (This proxy server, for "we" is not aware of (we can only perceive the access is Baidu's server, do not know the intermediary also has a proxy server to do load balancing). )

This proxy server, for "Server1 Server2 Server3" is perceptible (proxy server load balancer is routed to different server)
is not perceptible to the human, but to the server can be perceived, we call him reverse proxy server

Summarize
Frankly speaking: "Forward", "reverse" is relative to the perception of people. People can feel the agent is a positive agent, the agent is not felt is the reverse proxy.

Second, the initial knowledge of Nginx and PHP-FPM
what Nginx is:
Nginx ("Engine X") is a high-performance HTTP and reverse proxy server as well as a IMAP/POP3/SMTP server.

What is php-fpm:
1. CGI, fast-cgi protocol

The history of CGI
The early webserver only processed static files such as HTML, but with the development of technology, dynamic languages such as PHP appeared.
Webserver can't handle it, how to do? Then give it to the PHP interpreter to handle it!
Handing the PHP interpreter a good deal, but how does the PHP interpreter communicate with webserver?
In order to solve the communication between different language interpreters ( such as PHP, Python interpreter) and webserver, a CGI protocol was present. As long as you follow the CGI protocol to write the program, you can implement the language interpreter and Webwerver communication. such as the PHP-CGI program.

the improvement of fast-cgi
With the CGI protocol, the PHP interpreter and webserver communication problems, Webserver finally can handle the dynamic language. However,every request received by Webserver will fork a CGI process and kill the process at the end of the request. With 10,000 requests, you need the fork, kill php-cgi process 10,000 times.

Have you found a waste of resources?
So, there was a modified version of CGI, fast-cgi. F ast-cgi每次处理完请求后,不会kill掉这个进程,而是保留这个进程,使这个进程可以一次处理多个请求。这样每次就不用重新fork一个进程了,大大提高了效率 .

2. What is PHP-FPM?
PHP-FPM is php-fastcgi Process Manager.
PHP-FPM is the implementation of FastCGI and provides the function of process management.
The process contains both the master process and worker process processes.
The master process has only one, which is responsible for listening to the port, receiving requests from the Web Server, while the worker process is typically multiple (the exact number is configured according to actual needs), and each process embeds a PHP interpreter inside, which is where the PHP code really executes.

Third, how to combine Nginx with PHP-FPM
As we said above, Nginx does not only handle the HTTP request function, but also can do the reverse proxy. Nginx uses the reverse proxy function to turn the dynamic request to the backend php-fpm.
Let's configure a new nginx+php-fpm

1. Configuring the Nginx.conf File
Enter the Nginx directory and edit the nginx.conf file.
, in the last line of nginx.conf, add an include file

2. Add the corresponding server
Enter the path to the include above and add a server.

Let's explain what the configuration item means:

server {    listen       ; #监听80端口, receive HTTP request    server_name  www.example.com; #就是网站地址    root/usr/local/etc/ Nginx/www/huxintong_admin; # Prepare the path to the code project    #路由到网站根目录www. example.com Time Processing location    /{        index index.php; #跳转到www. example.com/index.php        autoindex on;    }       #当请求网站下php文件的时候, reverse proxy to PHP-FPM location    ~ \.php$ {        include/usr/local/etc/nginx/fastcgi.conf; # Loading Nginx fastcgi module        fastcgi_intercept_errors on;        Fastcgi_pass   127.0.0.1:9000; #nginx the IP address and port that the fastcgi process listens on    }}

In summary: When we visit www.example.com, the process is this:

www.example.com        |        |      Nginx        |        | Route to www.example.com/index.php        |        | Loading nginx fast-cgi Module        |        | fast-cgi monitor 127.0.0.1:9000 Address        |        |www.example.com/index.php request arrives 127.0.0.1:9000        |        |     Waiting to be processed ...

Below we enable PHP PHP-FPM to handle this request

Opening the php-fpm.conf file, we see the following configuration:

That is: The PHP-FPM module listens to the 127.0.0.1:9000 port, waits for request to come and go processing.

Iv. Summary
The combination of Nginx and PHP-FPM, the complete process is this.

www.example.com        |        |      Nginx        |        | Route to www.example.com/index.php        |        | Loading nginx fast-cgi Module        |        | fast-cgi monitor 127.0.0.1:9000 Address        |        |www.example.com/index.php request arrives 127.0.0.1:9000        |        | PHP-FPM Monitor 127.0.0.1:9000        |        | PHP-FPM receive request, enable worker process processing Request        |        | PHP-FPM finished processing the request, return to Nginx        |        | Nginx returns the result to the browser via HTTP

Five, the effect shows
1. Start Nginx and PHP-FPM module

Start successfully, we view the PHP-FPM process

For example, there is a master process, 3 worker processes.

2. Create a file in the site Directory
We edit files such as:

3. Visit the website

Related Article

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.