国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial [Translation][php extension development and embedded] Chapter 13-php INI settings

[Translation][php extension development and embedded] Chapter 13-php INI settings

Feb 10, 2017 am 10:17 AM
php


INI setting

and the previous one Like the superglobal variables and persistent constants you saw in Chapter 1, php.ini values ??must be defined in the extended MINIT block. However, unlike other features, the definition of INI options consists only of simple start/stop lines. .

PHP_MINIT_FUNCTION(sample4)
{
    REGISTER_INI_ENTRIES();
    return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(sample4)
{
    UNREGISTER_INI_ENTRIES();
    return SUCCESS;
}

Define and access INI settings

The INI instruction itself is above the MINIT function in the source code file, use The following macros are defined completely independently. One or more INI instructions can be defined between these two macros:

PHP_INI_BEIGN()
PHP_INI_END()

These two macro functions are similar to ZEND_BEGIN_MODULE_GLOBALS()/ZEND_END_MODULE_GLOBALS(). However, this is not a typdef structure, but a framework organization for the definition of static data instances:

static zend_ini_entry ini_entries[] = {
{0,0,NULL,0,NULL,NULL,NULL,NULL,NULL,0,NULL,0,0,NULL} };

As you can see, it defines a vector of zend_ini_entry values, ending with an empty record. This is the same as the static you saw earlier The definition of vector function_entry is consistent.

##Simple INI settings

Now, you already have an INI structure for It is used to define INI instructions and the mechanism for engine registration/uninstallation of INI settings, so we can actually define some INI instructions for your extension. Suppose your extension exposes a greeting function, just like Chapter 5 "Your The same as in the first extension", but you can customize it if you want to say hello:

PHP_FUNCTION(sample4_hello_world)
{
    php_printf("Hello World!\n");
}

The simplest and most direct way is to define an INI command and give it a default value "Hello world!":

##

#include "php_ini.h"
PHP_INI_BEGIN()
    PHP_INI_ENTRY("sample4.greeting", "Hello World",
                                    PHP_INI_ALL, NULL)
PHP_INI_END()

As you may have guessed, the first two parameters of this macro Indicates the name of the INI instruction and its default value. The third parameter is used to determine whether the engine allows this INI instruction to be modified (this will involve the access level issue introduced later in this chapter). The last parameter is a callback function, which Will be called every time the value of the INI directive changes. You will see the details of this parameter in the Modification Events section.

Translation Note: If you and the translator When you encounter results that are inconsistent with the expected results of the original work, please add a "REGISTER_INI_ENTRIES();" call to your MINIT() function during testing, and make sure that the call is executed after allocating global space in your MINIT.

Now that your INI settings have been defined, you just need to use them in your greeting function.

PHP_FUNCTION(sample4_hello_world)
{
    const char *greeting = INI_STR("sample4.greeting");
    php_printf("%s\n", greeting);
}

Be sure Note that the value of char * is owned by the engine and must not be modified. Because of this, define your local variable used to temporarily store INI setting values ??as const. Of course, not all INI values ??are strings; There are other macros for getting integer, floating point and boolean values:

long lval = INI_INT("sample4.intval");
double dval = INI_FLT("sample4.fltval");
zend_bool bval = INI_BOOL("sample4.boolval");

Usually what you want to know is the current value of the INI setting; however, as a supplement, there are several macros that can be used to read the unmodified INI setting value:

const char *strval = INI_ORIG_STR("sample4.stringval");
long lval = INI_ORIG_INT("sample4.intval");
double dval = INI_ORIG_FLT("sample4.fltval");
zend_bool bval = INI_ORIG_BOOL("sample4.boolval");

In this example, the name of the INI instruction "sample4.greeting" adds the extension name as a prefix to ensure that it will not conflict with the INI instruction names exposed by other extensions. For private extensions , this prefix is ??not required, but is encouraged for public extensions for commercial or open source releases.

Access Level

For INI instructions, there is always a default value to start with. In most cases, the ideal is to leave the default value unchanged; however, for some special circumstances or specific actions within the script, these values ??may Needs to be modified. As shown in the following table, the value of the INI instruction may be modified at the following three points:



某些設置如果可以在任何地方被修改就沒有多大意義了, 比如safe_mode, 如果可以在任何地方去修改, 那么惡意腳本的作者就可以很簡單的去禁用safe_mode, 接著去讀或修改本不允許操作的文件.

類似的, 某些非安全相關的指令比如register_globals或magic_quotes_gpc, 在腳本中不能被修改, 因為, 在腳本執(zhí)行時, 它所影響的事情已經(jīng)發(fā)生過了.

這些指令的訪問控制是通過PHP_INI_ENTRY()的第三個參數(shù)完成的. 在你前面例子中, 使用了PHP_INI_ALL, 它的定義是一個位域操作: PHP_INI_SYSTEM | PHP_INI_PERDIR | PHP_INI_USER.

對于register_globals和magic_quotes_gpc這樣的指令, 定義的訪問級別為PHP_INI_SYSTEM | PHP_INI_PERDIR. 排除了PHP_INI_USER將導致以這個名字調(diào)用ini_set()時最終會失敗.

現(xiàn)在, 你可能已經(jīng)猜到, safe_mode和open_basedir這樣的指令應該僅被定義為PHP_INI_SYSTEM. 這樣的設置就確保了只有系統(tǒng)管理員可以修改這些值, 因為只有它們可以訪問修改php.ini或httpd.conf文件中的配置.

修改事件

當INI指令被修改時, 無論是通過ini_set()函數(shù)還是某個perdir指令的處理, 引擎都會為其測試OnModify回調(diào). 修改處理器可以使用ZEND_INI_MH()宏定義, 并通過在OnModify參數(shù)上傳遞函數(shù)名附加到INI指令上:

ZEND_INI_MH(php_sample4_modify_greeting)
{
    if (new_value_length == 0) {
        return FAILURE;
    }
    return SUCCESS;
}
PHP_INI_BEGIN()
    PHP_INI_ENTRY("sample4.greeting", "Hello World",
            PHP_INI_ALL, php_sample4_modify_greeting)
PHP_INI_END()

通過在new_value_length為0時返回FAILURE, 這個修改處理器禁止將greeting設置為空字符串. ZEND_INI_MH()宏產(chǎn)生的整個原型如下:

int php_sample4_modify_greeting(zend_ini_entry *entry,
    char *new_value, uint new_value_length,
    void *mh_arg1, void *mh_arg2, void *mh_arg3,
    int stage TSRMLS_DC);

各個參數(shù)的含義見下表:


Access Level

Meaning

SYSTEM

is located in php.ini#, or in the httpd.conf configuration file of apache and External directive,affects the startup phase of the engine , can be considered as INI#"global"Value

.

##PERDIR

###

is located in the httpd.conf configuration file of Apache and in the directive , or the directory or virtual directory where the request script is located The .htaccess file under the host and other apacheINI## set elsewhere before processing the request #Command.

##USER

Once the script starts executing

, can only be modified by calling the user space function ini_set() INIset.


核心結(jié)構(gòu)體: zend_ini_entry

struct _zend_ini_entry {
    int module_number;
    int modifiable;
    char *name;
    uint name_length;
    ZEND_INI_MH((*on_modify));
    void *mh_arg1;
    void *mh_arg2;
    void *mh_arg3;

    char *value;
    uint value_length;

    char *orig_value;
    uint orig_value_length;
    int modified;

    void ZEND_INI_DISP(*displayer);
};

展示INI設置

在上一章, 你看到了MINFO函數(shù)以及相關的指令用于展示擴展的信息. 由于擴展暴露INI指令是很常見的, 因此引擎提供了一個公共的宏可以放置到PHP_MINFO_FUNCTION()中用于展示INI指令信息.

PHP_MINFO_FUNCTION(sample4)
{
    DISPLAY_INI_ENTRIES();
}

這個宏將迭代PHP_INI_BEGIN()和PHP_INI_END()宏之間定義的INI指令集和, 在一個3列的表格中展示它們的INI指令名, 原始值(全局的), 以及當前值(經(jīng)過PERDIR指令或ini_set()調(diào)用修改后)

默認情況下, 所有的指令都直接以其字符串形式輸出. 對于某些指令, 比如布爾值以及用于語法高亮的顏色值, 則在展示處理時應用了其他格式. 這些格式是通過每個INI設置的顯示處理器處理的, 它和你看到的OnModify一樣是一個動態(tài)的回調(diào)函數(shù)指針.

顯示處理器可以使用PHP_INI_ENTRY()宏的擴展版指定, 它接受一個額外的參數(shù). 如果設置為NULL, 則使用展示字符串值的處理器作為默認處理器:

PHP_INI_ENTRY_EX("sample4.greeting", "Hello World", PHP_INI_ALL,
    php_sample4_modify_greeting, php_sample4_display_greeting)

顯然, 需要在INI設置定義之前聲明這個函數(shù). 和OnModify回調(diào)函數(shù)一樣, 這可以通過一個包裝宏以及少量編碼完成:

#include "SAPI.h" /* needed for sapi_module */
PHP_INI_DISP(php_sample4_display_greeting)
{
    const char *value = ini_entry->value;

    /* 選擇合適的當前值或原始值 */
    if (type == ZEND_INI_DISPLAY_ORIG &&
        ini_entry->modified) {
        value = ini_entry->orig_value;
    }

    /* 使得打招呼的字符串粗體顯示(當以HTML方式輸出時) */
    if (sapi_module.phpinfo_as_text) {
        php_printf("%s", value);
    } else {
        php_printf("<b>%s</b>", value);
    }
}

綁定到擴展的全局空間

所有的INI指令都在Zend引擎內(nèi)有一塊存儲空間, 可以用以跟蹤腳本內(nèi)的變更并進行請求外部的全局設置維護. 在這塊存儲空間中, 所有的INI指令都以字符串值存儲. 你已經(jīng)知道了, 這些值可以使用INI_INT(), INI_FLT(), INI_BOOL()等宏函數(shù), 很簡單的翻譯成其他的標量類型.

這個查找和轉(zhuǎn)換過程由于兩個原因非常低效: 首先, 每次一個INI的值在獲取時, 它必須通過名字在一個HashTable中進行定位. 這種查找方式對于僅在運行時編譯的用戶空間腳本而言是沒有問題的, 但是對于已編譯的機器代碼源, 運行時做這個工作就毫無意義.

每次請求標量值的時候都需要將底層的字符串值轉(zhuǎn)換到標量值是非常低效的. 因此我們使用你已經(jīng)學習過的線程安全全局空間作為存儲媒介, 每次INI指令值變更時更新它即可. 這樣, 所有訪問INI指令的代碼都只需要查找你的線程安全全局空間結(jié)構(gòu)體中的某個指針即可, 這樣就獲得了編譯期優(yōu)化的優(yōu)點.

在你的php_sample4.h文件MODULE_GLOBALS結(jié)構(gòu)體中增加const char *greeting; 接著更新sample4.c中的下面兩個方法:

ZEND_INI_MH(php_sample4_modify_greeting)
{
    /* Disallow empty greetings */
    if (new_value_length == 0) {
        return FAILURE;
    }
    SAMPLE4_G(greeting) = new_value;
    return SUCCESS;
}
PHP_FUNCTION(sample4_hello_world)
{
    php_printf("%s\n", SAMPLE4_G(greeting));
}

由于這是對INI訪問的一種非常常見的優(yōu)化方式, 因此引擎暴露了一組專門處理INI指令到全局變量的綁定宏:

STD_PHP_INI_ENTRY_EX("sample4.greeting", "Hello World",
    PHP_INI_ALL, OnUpdateStringUnempty, greeting,
    zend_sample4_globals, sample4_globals,
    php_sample4_display_greeting)


這個宏執(zhí)行和上面你自己的php_sample4_modify_greeting相同的工作, 但它不需要OnModify回調(diào). 取而代之的是, 它使用了一個泛化的修改回調(diào)OnUpdateStringUnempty, 以及信息應該存儲的空間. 如果要允許空的greeting指令值, 你可以直接指定OnUpdateString替代OnUpdateStringUnempty.

類似的, INI指令也可以綁定long, double, zend_bool的標量值. 在你的php_sample4.h中MODULE_GLOBALS結(jié)構(gòu)體上增加幾個字段:

long mylong;
double mydouble;
zend_bool mybool;

現(xiàn)在在你的PHP_INI_BEGIN()/PHP_INI_END()代碼塊中使用STD_PHP_INI_ENTRY()宏創(chuàng)建新的INI指令, 它和對應的_EX版本的宏的區(qū)別只是顯示處理器以及綁定到的值不同.

STD_PHP_INI_ENTRY("sample4.longval", "123",
    PHP_INI_ALL, OnUpdateLong, mylong,
    zend_sample4_globals, sample4_globals)
STD_PHP_INI_ENTRY("sample4.doubleval", "123.456",
    PHP_INI_ALL, OnUpdateDouble, mydouble,
    zend_sample4_globals, sample4_globals)
STD_PHP_INI_ENTRY("sample4.boolval", "1",
    PHP_INI_ALL, OnUpdateBool, mybool,
    zend_sample4_globals, sample4_globals)

這里要注意, 如果調(diào)用了DISPLAY_INI_ENTRIES(), 布爾類型的INI指令"sample4.boolval"將和其他設置一樣, 被顯示為它的字符串值; 然而, 首選的布爾值指令應該被顯示為"on"或"off". 要使用這些更加表意的顯示, 你可以使用STD_PHP_INI_ENTRY_EX()宏并創(chuàng)建顯示處理器, 或者使用另外一個宏:

STD_PHP_INI_BOOLEAN("sample4.boolval", "1",
    PHP_INI_ALL, OnUpdateBool, mybool,
    zend_sample4_globals *, sample4_globals)

這個特定類型的宏是布爾類型特有的, 它提供的是將布爾值轉(zhuǎn)換為"on"/"off"值的顯示處理器.

小結(jié)

在本章, 你了解了php語言中最古老的特性之一的實現(xiàn), 它也是阻礙php可移植的罪魁. 對于每個新的INI設置, 都會使得編寫可移植代碼變得更加復雜. 使用這些特性要非常慎重, 因為擴展以后時鐘都要使用它了. 并且, 在使用時要注意不同系統(tǒng)間的行為一致性, 以免在維護時出現(xiàn)不可預期的狀況.

接下來的三張, 我們將深入到流API, 開始使用流的實現(xiàn)層和包裝操作, 上下文, 過濾器等.

以上就是[翻譯][php擴展開發(fā)和嵌入式]第13章-php的INI設置?的內(nèi)容,更多相關內(nèi)容請關注PHP中文網(wǎng)(miracleart.cn)!


Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

See all articles
  • 參數(shù)名

    含義

    entry

    Points to the actual storage of the engineINIInstruction item.This structure provides Current value , original value , belonging module , and some other codes below (zend_ini_entrystructure structure)Listed information

    new_value

    The value to be set.If the processor returnsSUCCESS,This value will be set to entry->value,At the same time if entry->orig_value is currently not set , will set the current value to entry->orig_value,and set entry->modifiedmarker.The length of this string is passed new_value_lengthPass .

    ##mh_arg1, 2, 3

    These 3 pointers correspond to the data pointers given when the INI instruction is defined (zend_ini_entryThe 3 members with the same name).In fact ,These values ??are used by the engine for internal processing,You don’t need to care about them.

    ##stage

    ##ZEND_INI_STAGE_

    series One of 5 values: STARTUP, SHUTDOWN, ACTIVATE, DEACTIVATE, RUNTIME. These constants correspond to MINIT, MSHUTDOWN, RINIT, RSHUTDOWN, and active script execution .