How PHP and FASTCGI/PHP-FPM work-the theoretical part does not involve experimentation

Source: Internet
Author: User
Tags apc php language php source code

Title: PHP Overview
Author: Zheng
Date: 2014-05-16
---------------

---| Thank you Marco Education |---

Cumago's career is plain sailing.

Mime,http,html

MIME:N enables HTTP to transmit non-textual information, such as mp3
http: can only parse HTML documents, for multimedia MP3, etc., the browser needs to install plug-ins or Web browser can be adjusted to match the Web program to decode
Note: The browser itself cannot play music, or it has its own plug-in, or other programs on the host can play music, and the browser can call this program to perform music playback
The server usually sends static text.

Static: Can be executed anywhere, no background database
html,mp3,jpeg,png,flv

Dynamic Web site: Need server to explain, have background database
Dynamic Web sites must be able to respond according to the application request, even depending on the content returned by different users, depending on the client's request to return different results

Client dynamic
Client dynamic is not recommended
Server-side dynamic
......

Applet
Java was very hot in the 2000! Run a Dynamic web site

The JVM is commonly known as a Java virtual machine, similar to VMware's virtual machine under Windows, except that VMware is virtual hardware to run programs, and the JVM is just a sandbox or a box running Java. A program that can run Java
Because Java needs to load Java classes and libraries, the life cycle of Java programs, and so on when it is running, the JVM is a virtualized environment for Java that compiles and runs everywhere.
Java programs must run on the JVM, and Java's dependency on the environment is hidden by the JVM.
Why Java can cross-platform, is because Java's official website provides the different platform Jvm,java virtual machine. That means that if Java is running on Windows, it's on Windows
Install a Windows JVM and install a Linux JVM if it is running on Linux. Thus Java can be run on different platforms and become flexible, making the JVM compatible with the OS platform

Because Java programs are running on a Java virtual machine, the client browser installs Java plug-ins, even if running a malicious virus program, but also to destroy the Java Virtual machine, will not damage the underlying system

Bottom-level difference: OS different

Virtual Machine

There are many languages that can develop web programs, but some programs are more suitable for developing Web applications.
Programming languages
  static languages: Compiled languages   ---> are strongly typed, only compile before running
  c c++ java
    Advantages: High efficiency, good performance
   Cons: Every change must be recompiled, long development cycle, maintenance costs.

  Dynamic languages: Explanatory language   ---> is weakly typed, does not need to be compiled, can be used with an interpreter.
  shell python perl ...
   Advantages: Easy maintenance, many modules, short development cycle, low maintenance costs
   disadvantages: Poor performance

Facebook: Both good performance and development cost small internal converter dynamic Language conversion to static language
Dynamic language---static language
PHP--->Hiphop--> C + +) _c++ is a static program that can be executed directly on the server side and will be fast.
Hiphop is an internal converter that converts the PHP language into the C + + language

In fact, dynamic languages should be used to develop dynamic websites, but not all dynamic languages are suitable for developing dynamic websites, such as Bash
First, the cost is small, the cycle is short, maintenance is more convenient
Second, closer to the user experience

The reason why there are so many languages on the Internet is because every language has a more suitable scene. No language is a winner, and no language is more suitable for all environments.
Bash
Bash is not suitable for dynamic Web sites, although it is also a dynamic language, but for the development of Web sites, the cycle will be very long, the internet also use bash to develop dynamic sites such as blogs.
Typically bash is an automated script, and Perl is an automated script that is more powerful than bash.
Java
Java itself is a complete language, not suitable for the development of web sites, but someone to Java provides a special class called JSP class, so that the Java runtime can be fully in the Java container
It's done. You can also quickly design your Web site using the JSP language. Need to rely on additional frameworks.
Php
There is a language that does not require an additional framework to design a Web site. This language is called PHP, because it is designed to do web site development, but there are ASP, ugly and unsafe things



Only the more suitable, not the most suitable
BASH: To implement system automation, but if you use bash to develop Web applications, the cycle can be long. In fact, there are: such as Tetris, forum
Perl: Modules
Python: module framework
Java: Development language, class JSP classes are quickly completed in the Web container: SSH
Ruby: Additional Framework for scripting languages: Rails

Development:
Basic algorithms
Algorithms, Data structures
Compilation principle

Student movement, first of all to open the field of vision, so that their own ability to do strong enough. This is the pre-
Later, we should focus more on the principle of the system, or the understanding of programming, so as to know how this program works

PHP was born in 1994 and appeared in php1.0 version
In 1997, a second version appeared php2.0
In the same year, the third release of php3.0 laid a solid foundation

PHP is hypertext perprocessor
Hypertext PHP Preprocessor

Static: Compiler
Dynamic: Interpreter

Dynamic Language:
First, the lexical analysis
followed by a grammatical analysis
And then build the execution path

Cgi
Protocol
It can let our front-end Web server process, according to the corresponding program, call the corresponding execution environment, to run the corresponding program files, and to run the results of running program Files retrieved
Such a protocol to the web process is the CGI

Web process: Depending on the corresponding program, the Web server process invokes the corresponding execution environment to run the corresponding program file, and can retrieve the display result of the running program file from the Web process.
This protocol is called the CGI protocol.


Web application, WebApp
refers to the Web program running on the server side, when the client accesses the page, this page is not directly returned to the client, but the server-side first call the corresponding file execution environment,
The result is formatted as an HTML document and then returned to the client.



System principle
Program principle

The difference between a programmer and an operational dimension
Programmers are responsible for writing programs that run with these programs.

Understanding development can be a different thing

Many of these programs are now developed in Python.
Like what:
Cloud computing Framework: Openstack, also developed using Python
Now many game programs Python
Server Automation Control script: Python
Automated Operations Framework: Python


The advent of Zend engine divides the execution of PHP into two parts, first compiled into binary format, and then executes binary files. 1997 Zend Engine released first version 1.0, born php4.0
The advent of the Zend engine divides the processing of PHP code into two phases, first parsing the PHP code and converting it into a binary format called Zend opcode (similar to Java bytecode)
and store it in memory, and the second stage uses the Zend engine to perform the opcode of the swap;

OpCode: Operation code
PHP is an interpreted language means that PHP developed by the program to do just need to interpret the PHP interpreter can be lexical analysis of the parsing and then execute
This process is very slow, then if you want to make it fast should be the PHP source code first converted to binary format like the compilation process, the PHP interpreter compiled and then go to execute
Binary program
PHP source code----> compiled in binary Format--binary format execution
In the future when we visit this PHP page, first compiled on the server, the first time access is slow, the second access is I directly assigned to this compiled binary format, the speed will be much faster
The compiled result is called opcode, or php's opcode,
Although the result of PHP compilation is binary format, but can not be executed, can be said to be similar to the binary format, this binary format can only run in the Zend engine.
Also similar to Java programs that run only in the JVM.

php's opcode
OpCode is a PHP script-compiled intermediate language, like Java's bytecode bytecode, or. NET MSI. PHP executes PHP script code generally through the following 4 steps
Specifically, it should be the PHP language engine Zend
1. Scanning (lexing)---Convert the PHP code to a language fragment (Tokens) scanning lexical scan
2. Parsing-converts tokens to a simple and meaningful expression value assigned to a variable
3. Compilation--compiles the expression into opcodes compilation
4. execution--executes opcodes sequentially, one at a time, enabling PHP scripts to execute the PHP script in sequence

PHP compilation results opcode are placed in the process of the address space or in memory.

OpCode is placed in memory.
User A and User B
have access to the same page 1.php
Assume
User A to the server to initiate a 1.php request, then the server will start a PHP process to respond to a user's request, first by Zend engine to the 1.php lexical analysis, parsing, and then compiled into
Opcode, and puts the results in the address space of the process.
After User B also initiates a request for the same page 1.php to the server, the server initiates another PHP process to respond to the B user's request, and Zend engine will follow the process
Lexical analysis, parsing, and compiling into opcode, caches the address space of memory in this process.
Conclusion: opcode sharing between processes is not possible

A detailed conclusion
User A and User B initiated the 1.php request page, the server side is not using the same PHP process to respond to
The 1.php needs to be compiled and executed by Zend engine to compile the compiled results opcode in the response process memory address space, which is
In response to the user process's address space. Then the opcode compiled by Zend engine cannot be shared between processes, and each time the same page is requested, recompilation is required
Each of these needs to be recompiled and then executed, so our PHP program is somewhat more efficient or slow to perform.
But within the same process is very fast, the same user access to the same file is accessed multiple times 2 times 3 times 10 times ... is fast because it can be executed directly by Zend engine without recompiling
Cons: Other processes accessing the same file will not be accelerated

PHP accelerator or opcode cache
So is there a mechanism that can compile once, all processes can share opcode, and no recompilation is required.
The answer is yes, that's the PHP accelerator.
PHP Accelerator principle: To provide a cache space, any process compiled opcode into the memory space, any process can be in this cache to read the compiled opcode. Can directly
Executed directly by Zend engine. It's going to be a lot faster.

Any process-compiled opcode is not placed in its own address space, but is placed in the cache space provided by another program, and this cache space can be shared between multiple PHP processes



The program that provides the cache space is called the PHP accelerator opcode cache.
APC Current APC version not suitable for php5.4
Eaccelerator not supported current version not updated
Xcache Fast and stable php Opcode cache
Zend Optimizer and Zend Guard Loader Zend optimizer free closed source


PHP is a dynamic language that can be used for Web site development, but PHP programs must be compiled at Zend Engine before execution.

MVC: Module View Controller

Cgi
Common Gateway Interface: A universal Gateway interface that enables a Web server to execute an application's interface with the backend application server in conjunction with the interface of the back-end application

Apache:web server provides static HTML document picture MP3 a server
If you want to execute a PHP program, you must have a PHP interpreter, this time how Apache can be combined with PHP, establish a relationship


Now make a hypothesis
If the Web server Apache is running, this time the user initiates a request. PHP page, Apache self-executing, so is to find PHP interpreter, to explain the PHP script and interpret the results
The Web service returned to Apache.


The simple point is that CGI is an interface, this interface can let our web program, PHP can not be explained by the script, through the CGI mechanism, forwarded after the backend Web site let PHP interpreter to explain, and return
to the Web server.


------------------------------------------------------
Three modes of apache+php
Cgi
Module
FASTCGI/FPM---NGINX+FASTCGI/FPM

How the Web server interacts with PHP
There are three ways of doing this:
The first way:
Based on CGI mode
The life cycle of the CGI process
If a user accesses our web server and requests a PHP page, the Web server initiates a new process to respond to the user's PHP request, but the Web server itself explains
PHP is not a program, so it will invoke the PHP interpreter to explain the code, return to the Web server, and then destroy the process, when the next user still request a PHP page, continue to create
A new process is then returned to the Web server, destroying the process. This is the case in the future, creating processes, destroying processes, creating processes, and destroying processes. Very often. is bound to Zhao server pressure

Assuming a prefork based working mode
If 200 requests are the requested PHP dynamic page at the same time, the number of processes that the server will run.
The answer is a 400 PHP process
Because Apache works in prefork mode, each PHP needs to use a process, and the dynamic PHP request will also create a new process.
If an Apache process requires 2M of memory space 0.5G
A PHP process requires 20M of memory space depending on the size of the requested page 4G
4.5G of space without a moment
Cons: Many processes are enabled, and the CGI process is created temporarily, and there is a apche to create and destroy the CGI process, which is slow to respond to PHP requests


CGI This mechanism is not a good mechanism for PHP, because to create a large number of CGI process destruction process, will be very frequently created and destroyed especially a large number of concurrent user access.

The second way:
DSO mechanism dynamic shared object
Php_mod PHP into a dynamic shared module of Apache
This mechanism, PHP is loaded into the Apache dynamic module
Pros: Instead of creating a CGI process, because it is enabled in the Apache module, you can respond to requests directly with the Apache process and then tune the CGI to interpret the code.
Disadvantage: The Apache process responds to dynamic requests and also handles static requests

Load balancing with DNS

Third load Balancing:
fastcgi/fpm
If Apache works in prefork mode of operation
is called pre-creation process, even if no user request, will create a few idle processes, when the user access, you can directly respond to the user's request. The speed will be fast
A process generates a thread and then processes the user request with a thread

FPM This mode is designed to solve the problem of CGI and loading PHP modules
First the CGI process is not created temporarily, it is pre-created
The second is to separate the dynamic request and the static request, without a process to deal with,
Both of these will greatly improve the response to the user's request

Dynamic response and static response, instead of processing a dynamic request and processing a static request

fpm-Fast PHP Module


------------------------------

apache+php
For RPM packages, you just need to install PHP. Note that previous versions of php5.3.3 do not support FPM and require patching to support, and later versions support FPM
[[email protected] yum.repos.d]# Yum install php php-mbstring
Php-mbstring: Support multi-string, generally install this package, support the internationalization of
[[email protected] yum.repos.d]# rpm-ql PHP
/etc/httpd/conf.d/php.conf #生成了一个web服务器的子配置文件
/usr/lib64/httpd/modules/libphp5.so #模块/compiled into a dynamic shared library
/var/lib/php/session #
/var/www/icons/php.gif #图标

Because this note is a record of PHP, so do not involve too much Apache just, follow up will have more Apache working mode, optimize
Parameters in the Apache configuration file
<ifmodule prefork.c>
Startservers 8
Minspareservers 5
Maxspareservers 20
Serverlimit 256
MaxClients 256
Maxrequestsperchild 4000
</IfModule>
Apache has three modes of operation
Prefork: It uses a process management approach, so it provides more reliable performance and better compatibility
Worker: It employs a threading control method that can save overhead and process more data than perfork, but is not very compatible, and many older programs do not work under the worker
Event: In the pilot phase, it allocates a different process pool for each task and should not be used at this time.

Command Httpd-l to get the current type of MPM used by Apache
[Email protected] ~]# httpd-l
Compiled in Modules:
Core.c
Prefork.c
Http_core.c
Mod_so.c

This article is from the "Zheng" blog, make sure to keep this source http://467754239.blog.51cto.com/4878013/1413239

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.