msgbartop
PHP语言, PHP扩展, Zend引擎相关的研究,技术,新闻分享 – 左手代码 右手诗
msgbarbottom

07 Nov 08 PHP的GET/POST等大变量生成过程

主要探讨了PHP的大变量的生成过程。另外如果你注意到, 当在表单中提交的input的name中如果有点号的时候, 在PHP中会自动把点号处理成下划线。并且你很想知道这是为什么,在什么时候发生的? 呵呵,本文也就这个问题做了回答。

首先明确一个问题,PHP的变量名中是不能包含点号的。 但是为了处理表单中的点号命名,PHP就会自动把点号(.)转换成下划线(_)。
要知道PHP是怎么处理的,首先我们要了解,$_GET, $_POST, $_COOKIE等变量的构造过程。
在每个请求到来以后,apache处理到response阶段的时候, 会将控制权交给PHP模块, PHP模块会在处理请求之前首先间接调用 php_request_startup (具体调用序列是send_php -> apache_php_module_main -> php_request_startup, 关于这部门可以参看我前面的文章( PHP Life Cycle) , 在php_request_startup中:

   int php_request_startup(TSRMLS_D)
{
    int retval = SUCCESS;

#if PHP_SIGCHILD
    signal(SIGCHLD, sigchld_handler);
#endif

    if (php_start_sapi() == FAILURE) {
        return FAILURE;
    }

    php_output_activate(TSRMLS_C);
    sapi_activate(TSRMLS_C);
    php_hash_environment(TSRMLS_C);

    zend_try {
        PG(during_request_startup) = 1;
        php_output_activate(TSRMLS_C);
        if (PG(expose_php)) {
            sapi_add_header(SAPI_PHP_VERSION_HEADER, sizeof(SAPI_PHP_VERSION_HEADER)-1, 1);
        }
    } zend_catch {
        retval = FAILURE;
    } zend_end_try();

    return retval;
}
   

注意其中的php_hash_environment(TSRMLS_C) 函数调用 , 这个函数就是在请求处理前, 初始化请求相关的变量的函数。
这个函数定义在: main/php_variables.c中 , 有兴趣的可以看看:

  int php_hash_environment(TSRMLS_D)
{
        char *p;
        unsigned char _gpc_flags[5] = {0, 0, 0, 0, 0};
        zend_bool jit_initialization = (PG(auto_globals_jit) && !PG(register_globals) && !PG(register_long_arrays));
        struct auto_global_record {
                char *name;
                uint name_len;
                char *long_name;
                uint long_name_len;
                zend_bool jit_initialization;
        } auto_global_records[] = {
                { "_POST", sizeof("_POST"), "HTTP_POST_VARS", sizeof("HTTP_POST_VARS"), 0 },
                { "_GET", sizeof("_GET"), "HTTP_GET_VARS", sizeof("HTTP_GET_VARS"), 0 },
                { "_COOKIE", sizeof("_COOKIE"), "HTTP_COOKIE_VARS", sizeof("HTTP_COOKIE_VARS"), 0 },
                { "_SERVER", sizeof("_SERVER"), "HTTP_SERVER_VARS", sizeof("HTTP_SERVER_VARS"), 1 },
                { "_ENV", sizeof("_ENV"), "HTTP_ENV_VARS", sizeof("HTTP_ENV_VARS"), 1 },
                { "_FILES", sizeof("_FILES"), "HTTP_POST_FILES", sizeof("HTTP_POST_FILES"), 0 },
        };
        size_t num_track_vars = sizeof(auto_global_records)/sizeof(struct auto_global_record);
        size_t i;

        /* jit_initialization = 0; */
        for (i=0; i<num_track_vars; i++) {
                PG(http_globals)[i] = NULL;
        }

        for (p=PG(variables_order); p && *p; p++) {
                switch(*p) {
                        case 'p':
                        case 'P':
                                if (!_gpc_flags[0] && !SG(headers_sent) && SG(request_info).request_method && !strcasecmp(SG(request_info).request_method, "POST")) {
                                        sapi_module.treat_data(PARSE_POST, NULL, NULL TSRMLS_CC);       /* POST Data */
                                        _gpc_flags[0] = 1;
                                        if (PG(register_globals)) {
                                                php_autoglobal_merge(&EG(symbol_table), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_POST]) TSRMLS_CC);
                                        }
                                }
                                break;
                   ....以下省略:
 }}}
 

到了这里说个题外话, 就是在php.ini中, 可以使用variables_order来控制PHP是否生成某个大变量,已经大变量的生成顺序。
关于顺序,就是说, 如果打开了auto_register_globals的情况下, 如果先处理p,后处理g,那么$_GET['a'],就会覆盖$_POST['a'];

可以看到,离成功不远了,sapi_module.treat_data 也就是php_default_treat_data,
在php_default_treat_data中,对于变量,都调用php_register_variable_safe来注册变量, 而php_register_variable_safe最终会调用php_register_variable_ex:

  PHPAPI void php_register_variable_ex(char *var, zval *val, zval *track_vars_array TSRMLS_DC)
{
    char *p = NULL;
    char *ip;       /* index pointer */
    char *index, *escaped_index = NULL;
    int var_len, index_len;
    zval *gpc_element, **gpc_element_p;
    zend_bool is_array = 0;
    HashTable *symtable1 = NULL;

    assert(var != NULL);

    if (track_vars_array) {
        symtable1 = Z_ARRVAL_P(track_vars_array);
    } else if (PG(register_globals)) {
        symtable1 = EG(active_symbol_table);
    }
    if (!symtable1) {
        /* Nothing to do */
        zval_dtor(val);
        return;
    }

    /*
     * Prepare variable name
     */

    /* ignore leading spaces in the variable name */
    while (*var && *var==' ') {
        var++;
    }

    /* ensure that we don't have spaces or dots in the variable name (not binary safe) */
    //特别注意以下这段。。。。
    for (p = var; *p; p++) {
        if (*p == ' ' || *p == '.') {
            *p='_';
        } else if (*p == '[') {
            is_array = 1;
            ip = p;
            *p = 0;
            break;
        }
  ....以下省略

呵呵,问题的原因找到了, 就是在php_register_variable的时候,会将(.)转换成(_).
最后,再介绍下$_REQUEST变量的生成, 其实很简单, 在php_hash_environment中的最后, 会调用 php_auto_globals_create_request("_REQUEST", sizeof("_REQUEST")-1 TSRMLS_CC)来注册_REQUEST大变量, 在php_auto_globals_create_request("_REQUEST", sizeof("_REQUEST")-1 TSRMLS_CC)中,只是简单的将$_GET, $_POST, $_COOKIE merge起来(G(http_globals)[TRACK_VARS_COOKIE]这部分,可以参看我较早前的) :

static zend_bool php_auto_globals_create_request(char *name, uint name_len TSRMLS_DC)
{
    zval *form_variables;
    unsigned char _gpc_flags[3] = {0, 0, 0};
    char *p;

    ALLOC_ZVAL(form_variables);
    array_init(form_variables);
    INIT_PZVAL(form_variables);

    for (p = PG(variables_order); p && *p; p++) {
        switch (*p) {
            case 'g':
            case 'G':
                if (!_gpc_flags[0]) {
                    php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]) TSRMLS_CC);
                    _gpc_flags[0] = 1;
                }
                break;                                                                                                                    case 'p':
            case 'P':
                if (!_gpc_flags[1]) {
                    php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_POST]) TSRMLS_CC);
                    _gpc_flags[1] = 1;
                }
                break;
            case 'c':
            case 'C':                                                                                                                         if (!_gpc_flags[2]) {
                    php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_COOKIE]) TSRMLS_CC);
                    _gpc_flags[2] = 1;
                }
                break;
        }
    }

    zend_hash_update(&EG(symbol_table), "_REQUEST", sizeof("_REQUEST"), &form_variables, sizeof(zval *), NULL);
    return 0;
}


分享到:



Related Posts:

Tags: , , ,

49 Responses to “PHP的GET/POST等大变量生成过程”

  1. 黄雪飞 |

    请问 TSRMLS_CC 是什么,起什么作用呢?

  2. 燕玉苗 |

    别的情况下无所谓,但是做签名验证的时候会导致bug,只能用php://input获取原始数据流

  3. Remona |

    Pets know who they are, and are qսite satisfied with һat knowing.
    Ꭰߋ уοu ѡant tо geet rid օf tҺе 186 MPH speed limiter.
    ΤҺᥱ range οf а hoverboard iss Һow far tɦе
    hoverboard will travel οn οne fupl chjarge before
    іt աill neеԁ recharrged ɑgain.

    Ηere іѕ mʏ homeplage …
    ѕеlf balancing scooter models (Remona)

  4. clash of clan tool |

    But like its greater cousin, the HTC Evo, it’s obvious that HTC crafted it with a focus on delivering
    a top-notch gamer experience. Track stats across multiple seasons and earn skills in competition against the worlds finest players.
    Immerse yourself in unprecedented football atmosphere and the
    true PES experience with PES 2011.

  5. voyage au vietnam formalités |

    Vietnam stretches over 1650 km over the eastern coast in the Indochinese
    Peninsula( from 8. There are some extra fees you must pay for example postal cost
    etc. The tombs of Tu Duc, Ming Mang and Khai Dinh will be the best-known and the majority visited.
    This is incredibly advantageous for anonymity
    online, no matter what you’re doing.

  6. voyage vietnam budget |

    It could be the fastest and reliable way for getting a Vietnam visa.
    Gravity, the group’s 11th album, was already released on 22
    November last year. They were serving our Nation in the Iraq and Afghanistan wars.
    For some, finding Vietnam small selection of travel firms
    may be challenging.

  7. vietnam travel destinations |

    This is legal process to have visa and is particularly licensed by the Immigration department of
    Vietnam. Vietnam tours are another name of fun and excitement.
    A 5-year-old Vietnamese boy died on Sunday evening after falling coming from a large kite.
    The place hosts at the least 2,200 plant species well
    as over 1,470 floral species.

  8. c1758702180703849849 |

    Within couple of seconds, they might be able to find out
    the many news of any happening in parcels of websites. All
    individuals need for being well-known about this news of kinds of happenings.
    It’s the smart solution with the owner, the retailer, edinburgh airport as well as the customer.
    Care have to be taken that there’s no misrepresentation of facts.

  9. Discover More |

    They daily check upcoming events to become located
    in Noida. He someday aspires to get his work included in a major teen magazine, including Pop – Star Magazine.

    Latest News in Kerala is in the rainy and monsoon reason the routes of trains gets affected.
    People, who deny knowing Hindi of the perception of division developed by states.

  10. Get More Information |

    One of which has become the author and also the other is among the
    most author’s mom. Hindi, the national language of India It is spoken by a lot more than 437 million people from the world.

    ” A most reputed option may be the breaking news India. Many often the latest gaming news issued is incorrect.

  11. Read This |

    Within couple of seconds, they are often able to find out every one of the news of each happening in several websites.
    The homepage itself displays precisely what is inside that website.
    Himachal Pradesh and Chhatisgarh are two states in India.
    This news provides each information regarding the
    stock market, the benefits or losses within the particular day.

  12. Additional Info |

    There a variety of sources present nowadays from which people will
    get instant news every one of the times. Today,
    Indian press includes a deep influence within the lives of an individual within this nation. ” A most reputed option could be the breaking news India. However, the infamous apple never was tested for cyanide.

  13. Going Here |

    We are usually in the travel industry over decade online.
    Thus, for any state there may be news that is delivered in local languages.
    These news, would later be discussed among themselves.
    A fence of info is formed due towards the importance of latest business news.

  14. Get More Info |

    Drum South Africa gives its readers stories they won. A majority on the Indian people trusts national
    newspapers. When it arrived at sports news especially cricket news,
    India is a frenzy nation. However, the infamous apple has never
    been tested for cyanide.

  15. Continue Reading |

    However, the area is not only tied to the education and theoretical areas of life.

    One thing that they was famous for wasn’t looking within the past to determine the
    future. School will be the guide coming from all students in succeeding as having
    it . good values and respect for others. So, in every single state there are several channels
    to supply news in regional languages.

  16. c8066147050874026694 |

    They daily check upcoming events for being stuck Noida. In this
    busy life folks don’t get long to for themselves. School will
    be the guide of most students to become anyone
    with good values and respect for others.
    Keeping abreast with all the latest Lebanon news happenings
    will be the easiest method to accomplish so.

  17. Additional Info |

    However, this line of business is not only just limited to
    the education and theoretical elements of life. A majority from the Indian people trusts
    national newspapers. The case of event has being chosen precisely don’t forget
    the quality of audience. They are, frequently, highly visible indicators we
    are desperate.

  18. Read Full Article |

    We have been around in the travel industry over a decade online.
    You will see great bargains on full bloods or percentages goats.
    When it arrived at sports news especially cricket news, India is
    a frenzy nation. any other generic clips that
    illustrate ideas in lieu of report events.

  19. Homepage |

    However, the sector is not merely tied to the education and theoretical issues with life.
    In addition towards the huge benefit for remaining
    anonymous there are several other benefits too. A Drum magazine
    digital subscription is available with just a
    click. Lifestyle news and Indian economy news they are both most demanded chapters of good news
    for people.

  20. Visit Website |

    Get ready to place a feeling on others with the complete expertise in current affairs.
    A majority from the Indian people trusts national newspapers.
    One thing I may do is read news stories about positive things.
    Today news can be purchased in each of the religion languages other than English and Hindi.

  21. c6163892242798518474 |

    Drum South Africa gives its readers stories they won. In India hundred of newspapers published
    in weekly basis and daily basis. There are many news channels in India
    to produce all sorts of latest news. 3) News media is repeated constantly, often in mind-numbing detail,
    often for trivial topics.

  22. Wayne |

    Thank you for the good writeup. It in reality was a enjoyment account it.

    Glance complicated to more added agreeable from you!
    However, how could we be in contact?

  23. additional reading |

    Reporting this information would be the role from the news media outlets.
    For lots of people per day is incomplete without reading the newspaper.
    ll can’t predict the number of future victims for these
    crimes might are already spared. The not so great affects everyone and also
    the first instinct should be to help by offering advice.

  24. Recommended Reading |

    Staggeringly enough, this might eventuate to the guy
    at any quinquennium. Other comments included “GOD is originating back therefore you Mr. Now the same eighths can market as low as $30, according on the Denver Post on June 22. Most preferred medium of news in India is online Hindi News.

  25. Click This Link |

    Publishers which have renedered the switch previously realized the huge benefits and profits.
    Kanchan Kumar Vaidya writes about “ daily news newspaper , Hindi news portal ,
    Hindi Samachar. The latest news coming our technique is
    that each one will not be well between Madhuri Dixit and Shri Ram Nene.

    They have started trying to find the entire world news online.

  26. helpful hints |

    “Why besides banned the flights and secure the borders. Phoenix News, it truly is limited by Chinese speaking audiences. The latest news coming our method is that each one is just not well between Madhuri Dixit and Shri Ram Nene. The reception from the general public wasoverwhelmingly positive.

  27. Recommended Reading |

    Drum South Africa gives its readers stories they won. Just while there is water doesn’t mean there might are already life on Mars.

    ll can’t say for sure what number of future victims of those crimes might
    have already been spared. Keywords: Petit, unlocked door, Crime, security, Walk-Ins.

  28. ”Joaca Hay Day si Descopera Fermierul din Tine” |

    Other hits include Duke Nukem, which achieved the very best of the charts for
    Arcade & Action games; Craneballs Studios’ Overkill (pictured at
    top rated), with greater than 900,000 consumers;
    Making Fun’s Santa’s Village, which has 680,000 customers.
    Games, for instance, must be entertaining with all the audios and visuals.
    There are two versions, one written in Python and one written in Objective C targeting i – OS.

  29. prizee triche jetons |

    This paragraph will help the internet visitors for setting up new weblog or even a blog from
    start to end.

  30. http://aimeeevergood.buzznet.com |

    And that’s the best part of it because on the website,
    you can be fairly confident the rest of the copy to stand out.

    State clearly and simply what you can do it again, and psychotherapist 9gag the mailer
    would be thrown away. You can actually play with it and psychotherapist 9gag it will pay big dividends
    for you. Just make sure that your mailing arrives on the first of the month may mean that you
    get information about.

  31. kontrola prędkości |

    Pretty great post. I simply stumbled upon your weblog and wanted
    to mention that I have really loved surfing around your weblog posts.

    After all I will be subscribing in your rss feed and I am hoping you write again soon!

    My website :: kontrola prędkości

  32. Jorja |

    Customers are able to find individuals writing on these discussion planks daily, or maybe we’re not talking
    maill at all. Tell them a good reason why it is always a good idea to do a comparison lead generation graphic design of
    costs from different direct mailing providers that catch
    your interest and contact them.

  33. Diana Radetsky |

    Hi there, I found your web site by means of Google at the same time as searching for a comparable
    matter, your web site came up, it seems good. I have bookmarked it in my google bookmarks.

    Hello there, just was aware of your weblog thru Google, and found
    that it’s truly informative. I’m gonna watch out for
    brussels. I’ll appreciate in the event you continue this in future.
    Numerous other people will be benefited from your writing.
    Cheers!

  34. games |

    There are various of good reasons which may be attributed to that undeniable link.
    Definitely the standard wage will always adhere to Clash of Clans Hack with the foreseeable future.
    The particular monetary click appears unable to make-up their brain on these concerns
    that unsettles buyers. In order to estimate one of the wonderful politics experts Odysseus Bootlegger ‘The achievement of any politics system could simply genuinely end up being examined in the event the extra fat woman has sung.
    a Surprisingly, he fresh practically nothing regarding Clash of Clans Hack until he / she has been effectively straight into
    their thirties. I’m strongly that when people in politics expended a smaller amount period thinking about Clash of Clans Hack and also fit additional hard work inside their household lifestyle,
    that we might have a very diverse nation.

    The reason why do Clash of Clans Hack combination the road?
    - To go to the opposite part! Simply just my personal
    small laugh, nevertheless let us expect that will Clash of Clans Hack won’t inspire similar hilarity over the following elections.
    I think Clash of Clans Hack should not be allowed to receive
    with respect to greater dilemma: why tend to be most of us right here?

    Placing this particular away the of fantastic relevance.

    The idea secures purchase, generates ‘fires’, plus it gives the most
    effective available within persons. I am going to leave the last
    word on the popular Beyonce De Niro: We requirement Clash
    of Clans Hack, nothing at all a lot more nothing at all a lesser amount of.

    Here is my web page :: games

  35. Mariusz Błaszczak |

    He said at Prime Minister’s Questions on Wednesday: “I certainly support No Smoking Day and, unlike in some previous years, I hope to meet its requirements in full. The strength of a woman is not measured by the impact that all her hardships in life have had on her; but the strength of a woman is measured by the extent of her refusal to allow those hardships to dictate her and who she becomes. Because of the reckless war policies instituted by the Bush administration, fewer Americans want to join the military, resulting in missed recruiting quotas.

    My blog – Mariusz Błaszczak

  36. http://www.escorts-leeds.co.uk |

    Thanks for your marvelous posting! I genuinely enjoyed reading it,
    you might be a great author. I will ensure that I bokkmark your blog and definitely will come back later on.
    I want to ecourage continue your gret writing, have a nice holiday weekend!

    My web-site leeds escort agency (http://www.escorts-leeds.co.uk)

  37. xiaolu |

    辛苦辛苦,我这边也在进行这项任务,对比你的阅读过程,有些受益。谢谢

  38. Thiniki's blog » PHP内核学习笔记—预定义变量的初始化 |

    [...]     下午睡觉睡不着,起来接着看PHP的内核,想要了解一下PHP中的预定义变量实现过程。对比Laruence的《PHP的GET/POST等大变量生成过程》及TIPI的《第三节 预定义变量》,$_POST、$_GET等预定义变量初始化的过程应该是通过php_request_startup()函数调用php_hash_environment()来进行初始化的。然而找到main/php_variables.c中的php_hash_environment()函数却是如下: [...]

  39. PHP的GET/POST等大变量生成过程 | 炮灰`Blog |

    [...] · 本文地址: http://www.laruence.com/2008/11/07/581.html · 转载请注明出处                                            [...]

  40. PHP的GET/POST等大变量生成过程 | 万维网黑客联盟 |

    [...] 本文地址: http://www.laruence.com/2008/11/07/581.html [...]

  41. bluesky |

    lz很强,十分崇拜,偶像!

  42. 深入理解PHP原理之变量生命期(一) | haohtml's blog |

    [...] 那么, 我们今天就重点关注下, Query String是如何构建成_GET数组的(关于GET变量的生成, 请一并阅读我之前的文章: “PHP的GET/POST等大变量生成过程“): [...]

  43. dyfire |

    楼主很强~。~

  44. 深入理解PHP原理之变量生命期(一) | 风雪之隅 |

    [...] 那么, 我们今天就重点关注下, Query String是如何构建成_GET数组的(关于GET变量的生成, 可以参看我之前的文章: “PHP的GET/POST等大变量生成过程“): [...]

  45. 个人简历 |

    贵站做的很好

  46. z.En |

    你简直就是我偶像

  47. jackywdx |

    呵呵,找到了,在php_globals.h里面定义的。
    #ifdef ZTS
    # define PG(v) TSRMG(core_globals_id, php_core_globals *, v)
    extern PHPAPI int core_globals_id;
    #else
    # define PG(v) (core_globals.v)
    extern ZEND_API struct _php_core_globals core_globals;
    #endif

  48. 雪候鸟 |

    PG是为了兼容线程安全模式的一种对php_globals的访问包装, 定义在 main/php_globals.h(php 5.x)

  49. jackywdx |

    想问个问题,PG作什么用的。
    宏的定义在哪,一直找不到

Leave a Reply

*