From the bottom of the PHP work principle to say

Source: Internet
Author: User
Tags end error handling execution final connect mysql net zend

I've done it before. Net,java developed, and also wrote several PHP sites, it seems that 3 major programming languages have been contacted. But it is increasingly felt that the whole process of programming lacks a whole understanding, especially the underlying mechanism. such as network programming, compiler principles, server-side, database storage engine principles. So read some books, the more classic with apue,unp,tcp/ip,nginx,mysql InnoDB storage engine, in-depth understanding of the JVM. Gradually found that no matter what language to do development, behind the Linux,shell,c/c++,nginx server, MySQL figure. Perhaps only the knowledge of these core principles, a programmer will have the core competitiveness.

The back end of bat is inseparable from these core technologies, but the front end (business logic layer) will be different. For example, Taobao mainly uses Java, Baidu mainly uses PHP. Tencent is a tool control group, mainly using C/s + + technology. Tencent's main products are all kinds of clients under Windows (QQ, Input method, music ...). The most important is the game) as well as the server side. Relatively speaking, the Web products are relatively few (QQ space, friends Network, etc.), these web products and more mature, but occasionally do some improvement. Unless new products appear, there will not be a large number of talent needs.

Although the current machine learning, large data mining field of talent demand seems more exuberant, but the relevant technology is still to be built on the LINUX,JVM above. Some companies ' demand for Java talent will grow further.

Now that you understand the C language compilation and connection process, the Java JVM operating mechanism, suddenly curious about the running process of PHP, mechanisms and principles. Find a few blog, probably understand a bit. Put it down first:

PHP Bottom Working principle

Brief Introduction
Let's take a look at the following procedure:

    We have never manually opened PHP related processes, it is running with the launch of Apache, PHP through the mod_php5.so module and Apache connection (specifically SAPI, that is, the server Application programming interface); PHP has a total of three modules: kernel, Zend engine, and the expansion layer; the PHP kernel is used to handle requests, file streams, error handling, and other related operations; the Zend Engine (ZE) is used to convert the source file into machine language and then run it on the virtual machine; the extension layer is a set of functions, class libraries, and streams that PHP uses to perform certain actions. For example, we need MySQL extensions to connect to the MySQL database; when Ze executes the program, it may need to connect several extensions, and Ze will give control to the extension, and so on, and then return it after processing a particular task. Finally, ZE returns the results of the program to the PHP kernel, which sends the results to the SAPI Final output to the browser.

    In-depth Discussion
    Wait, it's not that simple. The above process is just a short version, let's dig deeper and see what's going on behind the scenes.

      When Apache starts, the PHP interpreter starts; PHP starts with two steps; The first step is to initialize some environment variables, which will take effect throughout the SAPI lifecycle; the second step is to generate some variable settings that are only for the current request.

      PHP Start the first step
      I don't know what the first and second step is. Don't worry, we'll discuss it in detail next. Let's take a look at the first step and the most important step. Keep in mind that the first step occurs before any request arrives.

        When you start Apache, the PHP interpreter starts, and PHP invokes the Minit method of each extension, which switches the extensions to the available state. See what extensions are open in the php.ini file; Minit means "module initialization." Each module defines a set of functions, class libraries, etc. to handle other requests.

        A typical Minit method is as follows:
        Php_minit_function (extension_name) {
        /* Initialize functions, classes etc * *
        }
        php start Step two

          When a page request occurs, the SAPI layer controls the control over the PHP layer. PHP then sets the environment variables needed to reply to this request. It also creates a variable table that holds the variable names and values that are generated during execution. PHP invokes the Rinit method of each module, that is, "request initialization." A classic example is the Rinit of the session module, which, if a session module is enabled in PHP.ini, initializes the $_session variable when the rinit of the module is invoked and reads the relevant content; The Rinit method can be seen as a preparation process, Will start automatically between execution of the program.

          A typical Rinit method is as follows:
          Php_rinit_function (extension_name) {
          /* Initialize Session variables, pre-populate variables, redefine global variables etc * *
          }
          PHP Close the first step
          Like PHP startup, PHP is closed in two steps:

            Once the page has been executed (whether it was executed to the end of the file or aborted with the exit or Die function), PHP starts the cleanup process. It invokes the Rshutdown method of each module in order. Rshutdown is used to clear the symbol table that is generated when the program is run, that is, to call the unset function on each variable.

            A typical Rshutdown method is as follows:
            Php_rshutdown_function (extension_name) {
            /* Do memory management, unset all variables used at the last PHP call etc * *
            }
            PHP Closes the second step
            Finally, all the requests have been processed and SAPI is ready to close, and PHP begins the second step:

              PHP invokes the Mshutdown method for each extension, which is the last chance for each module to release memory.

              A typical Rshutdown method is as follows:
              Php_mshutdown_function (extension_name) {
              /* Free handlers and persistent memory etc * *
              }
              In this way, the entire PHP lifecycle is over. Note that the start first step and close second step are performed only if the server does not request it.

              The following is illustrated with a few illustrations!

              PHP Bottom Working principle

              Figure 1 PHP structure

              As you can see from the diagram, PHP is a 4-tier system from bottom to top.

              ①zend engine

              Zend Whole with pure C implementation, is the kernel part of PHP, it will PHP code translation (lexical, parsing, such as a series of compiling process) for the implementation of opcode processing and implement the corresponding processing methods, the implementation of the basic data structure (such as Hashtable, OO), memory allocation and management, Provides the corresponding API method for external call, is the core of all, all the peripheral functions are implemented around Zend.

              ②extensions

              Around the Zend Engine, extensions provides a variety of basic services through a modular approach, our common built-in functions (such as array series), standard libraries, and so on are implemented through extension, and users can also implement their own extension as needed to achieve functional expansion , performance optimization and other purposes (such as paste is using the PHP middle tier, Rich text parsing is the typical application of extension).

              ③sapi

              SAPI full name is the server application programming Interface, which is the service-side application programming interface, SAPI through a series of hook functions, so that PHP can interact with the perimeter data, which is a very elegant and successful PHP design, By SAPI the PHP itself and the top application decoupling isolation, PHP can no longer consider how to be compatible with different applications, and the application itself can be implemented in accordance with their own characteristics of different ways. The following will be covered in the SAPI section

              ④ Upper Application

              This is what we usually write PHP programs, through different sapi ways to get a variety of application patterns, such as through the webserver to implement Web applications, the command line to run the script and so on.

              frame of mind:

              Engine (Zend) + component (EXT) mode reduces internal coupling

              Middle tier (SAPI) isolate Web server and PHP

              **************************************************************************

              If PHP is a car, then

              The frame of the car is PHP itself.

              Zend is the engine of the car (engine)

              The various components below ext are the wheels of the car

              SAPI can be seen as highways, cars can run on different types of highways.

              And the execution of a PHP program is that the car runs on the road.

              So we need: excellent engine + proper wheels + right runway

              the relationship between Apache and PHP

              The Apache parsing of PHP is done through a number of PHP module in the module.

              The final integration of PHP into the Apache system, but also need to make some necessary Apache settings. Here, we will use PHP MOD_PHP5 SAPI running mode as an example to explain, as for the sapi of the concept behind we'll explain in detail.

              Assuming that the version we installed is Apache2 and PHP5, you need to edit the Apache main configuration file http.conf, adding the following lines:

              Under Unix/linux Environment:

              LoadModule Php5_module modules/mod_php5.so

              AddType application/x-httpd-php. php

              Note: Where modules/mod_php5.so is the installation location of mod_php5.so files in the X system environment.

              In Windows environment:

              LoadModule Php5_module D:/php/php5apache2.dll

              AddType application/x-httpd-php. php

              Note: D:/php/php5apache2.dll is where the Php5apache2.dll files are installed in the Windows environment.

              These two configurations are to tell Apache Server, later received the URL user request, usually in PHP as a suffix, you need to call the Php5_module module (mod_php5.so/php5apache2.dll) for processing.

              The life cycle of Apache

              Apach process of request processing

              Apache Request processing Loop detailed
              What do the 11 phases of the Apache request processing loop do? (Are these 11 stages the corresponding 11 processing stages in Nginx??? ) <喎?http: www.2cto.com kf ware vc " target="_blank" class="keylink"> vcd4kpha+cjgholbvc3qtumvhzc1szxf1zxn0vde2zjwvcd4kpha+ciagicdu2tx9s6ph68fztkba7ch3s8zw0kos1elkx8sjv+m/ ydlusuxi67mz19o1xlxa0ru49r3xts6ho7bu09rex9cpz+u63ntnvfji67smwo3h68fztcteo7/pwltltaos1ek49r3xts6/ydlusbva+ 9pdoam8l3a+cjxwpgogicagmqgivvjjifryyw5zbgf0aw9uvde2zia8yni+ciagicbbcgfjagxu2rg+vde2zrxe1vfsqrmk1/ejur2rx+ vh87xevvjm07pj5lw9sb612m7evp7ptc2zoapeo7/pv8ns1nta1ek917bosuxi67mz19ojrna00ndx1ly6tctts8nkwt+ 8ragjbw9kx2fsawfzvs3kx8d708pv4rj2vde2zrmk1/e1xkgjpc9wpgo8cd4kicagidohokhlywrlcibqyxjzaw5nvde2zia8yni+ ciagicbbcgfjagxu2rg+vde2zrxe1vfsqrmk1/ejurzssunh68fztctnt7k/oaptydpaxko/6b/j0ttu2sfrx/ o0psdtwfezzlxeym66ztk7upa148np1rtq0lzssunh68fzzbeyv7xeym7o8aos0vk0y9xiupa5s9ftutzj2bg7yrntw6gjbw9kx3nldgvudmlmvs3kx8d708p V4rj2vde2zrmk1/e1xkgjpc9wpgo8cd4kicagidshokfjy2vzcybdb250cm9svde2zia8yni+ciagicbbcgfjagxu2rg+vde2zrxe1vfsqrmk1 /ejurj5vt3f5nbdzss8/rzssunkx7fx1mrq7bfdzsrh68fztctxyts0oanbcgfjagw1xlhq17zc37ytyrxp1shl1mrq7brnvty++ Na4we6ho21vzf9hdxroel9ob3n0vs3kx8d708pv4rj2vde2zrmk1/e1xkgjpc9wpgo8cd4kicagidwhokf1dghlbnrpy2f0aw9uvde2zia8yni+ Ciagicagqxbhy2hl1nqxvr3xts61xnb30qq5pnf3o7qwtnxvxetww87evp7j6laotcsy38luttttw7unvfjq0mjp1qsjrlkiyei2qnpdu6fd+ 8f40/kho8sjv+m/ Ydlu1nrv4r3xts6y5cjrubpx06osyrxp1tk7upbiz9akt723qkgjpc9wpgo8cd4kicagidahokf1dghvcml6yxrpb26917boidxicj4kicagiefwywnozdtas b6917botctw99kquatx96o6upm+3cxk1spoxlz+voyy6crht/huytdtym/wpln9tcttw7un1rtq0mfrx/o1xllz1/eho8sjv+m/ ydlu1nrv4r3xts6y5cjrubpx06osyrxp1tk7upbtw7unykjp3rncwo21xle9t6ihozwvcd4kpha+ ciagica3oajnsu1fifr5cgugq2hly2tpbme917boidxicj4kicagiefwywnozdtasb6917botctw99kquatx96o6upm+3cfrx/ pxyts0tcrnsu1fwodqzbxez+c52lnm1pkjrmxqtqi9q9kqyrntw7xexnri3bsmwo26r8r9oaox6te8xko/ 6w1vzf9uzwdvdglhdglvbrrnbw9kx21pbwxktc/wwcvv4rj2ubpx06gjpc9wpgo8cd4kicagidihokzpefvwvde2zia8yni+ ciagicdv4srh0ru49s2o08o1xl3xts6jrntk0o3eo7/ P1nre2sjdyfqzycb31q7hskos1mvq0mjous6x2nkqtcs0psdtwfezzkgjus1qb3n0x1jlywrfumvxdwvzdmdgjimymdi4ndujrnxiysfsu7j2xny5u7k2u /hizrro0mxporxeubpx06os0rlkx9fus6pkudpdtcs5s9ftoam8l3a+cjxwpgogicagoagiumvzcg9uc2w917boidxicj4kicagiefwywnozdtasb6917botctw99kquatx96o6yfqzybe1u9i/zbuntsu1xmtayn2jrli61pc4+l/ nu6e2y7eiy83su7j2x6g1sbxeu9i4tkgj1ek49r3xts7kx9x7upa0psdtwfezzlxeusvqxlk/t9ahozwvcd4kpha+ Ciagicaxmkgitg9nz2luz73xts4gpgjypgogicagqxbhy2hl1nqxvr3xts61xnb30qq5pnf3o7ru2rvyults0b6tt6llzbj4v827p7bl1q6687zhwrzkws7xo apeo7/pv8ne3ndeums78txfzoa7u0fwywnozbxeserxvmjv1r68x8k8oam8l3a+ cjxwpgoxmagiq2xlyw5vcl3xts4gpgjypgogicagqxbhy2hl1nqxvr3xts61xnb30qq5pnf3o7rh5cdtsb60zsfrx/ pkws7xtkba7c3qs8nwrrrz0sxb9lxeu7e+s6osscji587evp6hoss/ wry1xlsmwo278txfu29ja2v0tcs52lhvtci1ykos1elkx0fwywnozdk7tm7h68fztkba7bxe1+6689k7upa917booam8l3a+ Cjxwpgo8c3ryb25npkxbtvc83lm5o7o8l3n0cm9uzz48l3a+cjxwpgo8aw1nihnyyz0= "/program/uploadpic/2014-6/ 201461113415766.gif "alt=" b 簗 ﹊ 萟? {鷌?? S-na-drag? " 瞝 _ is 鷌 coarse 铻 to 凓 嗃 i 耉 "" y?m4 "Duan" Yo "http://www.2cto.com/kf/qianduan/css/". target=

              Baidu Research and Development Center blog http://stblog.baidu-tech.com/?p=763

              Wang Xingbin's Blog http://blog.csdn.net/wanghao72214/article/details/3916825



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.