search

PHP hooks

Jul 28, 2020 pm 04:47 PM
phphook

PHP hooks

Hooks provided by PHP

PHP and Zend Engine provide many different hooks for extensions that allow extension developers Control the PHP runtime in a way that PHP userland cannot provide.

This chapter will show various hooks and common use cases from extension hooks to them.

The general pattern for hooking into PHP functionality is to extend override function pointers provided by PHP core. The extension function then typically does its own work and calls the original PHP core functions. Using this pattern, different extensions can override the same hook without causing conflicts.

Related learning recommendations: PHP programming from entry to proficiency

Hooking to the execution of functions

## Execution of #userland and internal functions is handled by two functions in the Zend engine, which you can replace with your own implementation. The main use cases for extensions that cover this hook are general function-level profiling, debugging, and aspect-oriented programming.

The hook is defined in

Zend/zend_execute.h:

ZEND_API extern void (*zend_execute_ex)(zend_execute_data *execute_data);ZEND_API extern void (*zend_execute_internal)(zend_execute_data *execute_data, zval *return_value);

If you want to overwrite these function pointers, you must do this in Minit because of the Other decisions are made ahead of time based on the fact that the pointer is overwritten.

The usual pattern for overwriting is this:

static void (*original_zend_execute_ex) (zend_execute_data *execute_data);static void (*original_zend_execute_internal) (zend_execute_data *execute_data, zval *return_value);void my_execute_internal(zend_execute_data *execute_data, zval *return_value);void my_execute_ex (zend_execute_data *execute_data);PHP_MINIT_FUNCTION(my_extension){
    REGISTER_INI_ENTRIES();

    original_zend_execute_internal = zend_execute_internal;
    zend_execute_internal = my_execute_internal;

    original_zend_execute_ex = zend_execute_ex;
    zend_execute_ex = my_execute_ex;

    return SUCCESS;}PHP_MSHUTDOWN_FUNCTION(my_extension){
    zend_execute_internal = original_zend_execute_internal;
    zend_execute_ex = original_zend_execute_ex;

    return SUCCESS;}

One drawback of overriding

zend_execute_ex is that it changes the behavior of the Zend Virtual Machine runtime to use recursion instead of Handles calls without leaving the interpreter loop. Additionally, PHP engines that do not override zend_execute_ex may also generate more optimized function call opcodes.

These hooks are very performance sensitive, depending on the complexity of the original function encapsulation code.

When overriding execution hooks, the extension can log

each function call, you can also override userland, core and Individual function pointers to extension functions (and methods). It has better performance characteristics if the extension only needs access to specific internal function calls.

#if PHP_VERSION_ID < 70200typedef void (*zif_handler)(INTERNAL_FUNCTION_PARAMETERS);#endif
zif_handler original_handler_var_dump;ZEND_NAMED_FUNCTION(my_overwrite_var_dump){
    // 如果我们想调用原始函数
    original_handler_var_dump(INTERNAL_FUNCTION_PARAM_PASSTHRU);}PHP_MINIT_FUNCTION(my_extension){
    zend_function *original;

    original = zend_hash_str_find_ptr(EG(function_table), "var_dump", sizeof("var_dump")-1);

    if (original != NULL) {
        original_handler_var_dump = original->internal_function.handler;
        original->internal_function.handler = my_overwrite_var_dump;
    }}

When overriding a class method, the function table can be found on

zend_class_entry:

zend_class_entry *ce = zend_hash_str_find_ptr(CG(class_table), "PDO", sizeof("PDO")-1);if (ce != NULL) {
    original = zend_hash_str_find_ptr(&ce->function_table, "exec", sizeof("exec")-1);

    if (original != NULL) {
        original_handler_pdo_exec = original->internal_function.handler;
        original->internal_function.handler = my_overwrite_pdo_exec;
    }}

When PHP 7 compiles PHP code, it first converts it into an abstract syntax tree (AST), and then finally generates opcodes that are persisted in Opcache.

zend_ast_processThe hook is called by every compiled script and allows you to modify the AST after it has been parsed and created.

This is one of the most complex hooks to use because it requires complete knowledge of the AST. Creating an invalid AST here may cause unexpected behavior or crashes.

Better take a look at a sample extension that uses this hook:

    Google Stackdriver PHP Debugger Extension
  • Stackdriver-based proof-of-concept with AST
Whenever a user script calls

include/require or its corresponding include_once/require_once, the PHP kernel will call this function at the pointer zend_compile_file to handle this request. The parameter is a file handle and the result is zend_op_array.

zend_op_array * my_extension_compile_file(zend_file_handle * file_handle,int类型);

There are two extensions in PHP core that implement this hook: dtrace and opcache.

- If you use the environment variable

USE_ZEND_DTRACE to start a PHP script and compile PHP with dtrace support, the dtrace_compile_file is used for Zend/zend_dtrace.c . - Opcache stores the op array in shared memory for better performance, so whenever a script is compiled, its final op array is served from cache rather than recompiled. You can find this implementation in
ext/opcache/ZendAccelerator.c. - The default implementation named
compile_file is part of the scanner code in Zend/zend_language_scanner.l.

Use cases for implementing this hook are Opcode Accelerating, PHP code encryption/decryption, debugging or profiling.

You can replace this hook at any time while the PHP process is executing, and all PHP scripts compiled after the replacement will be handled by the hook's implementation.

It is very important to always call the original function pointer, otherwise PHP will no longer be able to compile the script and Opcache will no longer work.

此处的扩展覆盖顺序也很重要,因为您需要知道是要在Opcache之前还是之后注册钩子,因为Opcache如果在其共享内存缓存中找到操作码数组条目,则不会调用原始函数指针。 Opcache将其钩子注册为启动后钩子,该钩子在扩展的minit阶段之后运行,因此默认情况下,缓存脚本时将不再调用该钩子。

调用错误处理程序时的通知

与PHP用户区set_error_handler()函数类似,扩展可以通过实现zend_error_cb钩子将自身注册为错误处理程序:

ZEND_API void(* zend_error_cb)(int类型,const char * error_filename,const uint32_t error_lineno,const char * format,va_list args);

type变量对应于E _ *错误常量,该常量在PHP用户区中也可用。

PHP核心和用户态错误处理程序之间的关系很复杂:

1.如果未注册任何用户级错误处理程序,则始终调用zend_error_cb
2.如果注册了userland错误处理程序,则对于E_ERRORE_PARSEE_CORE_ERRORE_CORE_WARNINGE_COMPILE_ERROR的所有错误E_COMPILE_WARNING始终调用zend_error_cb挂钩。
3.对于所有其他错误,仅在用户态处理程序失败或返回false时调用zend_error_cb

另外,由于Xdebug自身复杂的实现,它以不调用以前注册的内部处理程序的方式覆盖错误处理程序。

因此,覆盖此挂钩不是很可靠。

再次覆盖应该以尊重原始处理程序的方式进行,除非您想完全替换它:

void(* original_zend_error_cb)(int类型,const char * error_filename,const uint error_lineno,const char * format,va_list args);void my_error_cb(int类型,const char * error_filename,const uint error_lineno,const char * format,va_list args){
    //我的特殊错误处理

    original_zend_error_cb(type,error_filename,error_lineno,format,args);}PHP_MINIT_FUNCTION(my_extension){
    original_zend_error_cb = zend_error_cb;
    zend_error_cb = my_error_cb;

    return SUCCESS;}PHP_MSHUTDOWN(my_extension){
    zend_error_cb = original_zend_error_cb;}

该挂钩主要用于为异常跟踪或应用程序性能管理软件实施集中式异常跟踪。

引发异常时的通知

每当PHP Core或Userland代码引发异常时,都会调用zend_throw_exception_hook并将异常作为参数。

这个钩子的签名非常简单:

void my_throw_exception_hook(zval * exception){
    if(original_zend_throw_exception_hook!= NULL){
        original_zend_throw_exception_hook(exception);
    }}

该挂钩没有默认实现,如果未被扩展覆盖,则指向NULL

static void(* original_zend_throw_exception_hook)(zval * ex);void my_throw_exception_hook(zval * exception);PHP_MINIT_FUNCTION(my_extension){
    original_zend_throw_exception_hook = zend_throw_exception_hook;
    zend_throw_exception_hook = my_throw_exception_hook;

    return SUCCESS;}

如果实现此挂钩,请注意无论是否捕获到异常,都会调用此挂钩。将异常临时存储在此处,然后将其与错误处理程序挂钩的实现结合起来以检查异常是否未被捕获并导致脚本停止,仍然有用。

实现此挂钩的用例包括调试,日志记录和异常跟踪。

挂接到eval()

PHPeval不是内部函数,而是一种特殊的语言构造。因此,您无法通过zend_execute_internal或通过覆盖其函数指针来连接它。

挂钩到eval的用例并不多,您可以将其用于概要分析或出于安全目的。如果更改其行为,请注意可能需要评估其他扩展名。一个示例是Xdebug,它使用它执行断点条件。

extern ZEND_API zend_op_array *(* zend_compile_string)(zval * source_string,char * filename);

挂入垃圾收集器

当可收集对象的数量达到一定阈值时,引擎本身会调用gc_collect_cycles()或隐式地触发PHP垃圾收集器。

为了使您了解垃圾收集器的工作方式或分析其性能,可以覆盖执行垃圾收集操作的函数指针挂钩。从理论上讲,您可以在此处实现自己的垃圾收集算法,但是如果有必要对引擎进行其他更改,则这可能实际上并不可行。

int(* original_gc_collect_cycles)(无效);int my_gc_collect_cycles(无效){
    original_gc_collect_cycles();}PHP_MINIT_FUNCTION(my_extension){
    original_gc_collect_cycles = gc_collect_cycles;
    gc_collect_cycles = my_gc_collect_cycles;

    return SUCCESS;}

覆盖中断处理程序

当执行器全局EG(vm_interrupt)设置为1时,将调用一次中断处理程序。在执行用户域代码期间,将在常规检查点对它进行检查。引擎使用此挂钩通过信号处理程序实现PHP执行超时,该信号处理程序在达到超时持续时间后将中断设置为1。

当更安全地清理或实现自己的超时处理时,这有助于将信号处理推迟到运行时执行的后期。通过设置此挂钩,您不会意外禁用PHP的超时检查,因为它具有自定义处理的优先级,该优先级高于对zend_interrupt_function的任何覆盖。

ZEND_API void(* original_interrupt_function)(zend_execute_data * execute_data);void my_interrupt_function(zend_execute_data * execute_data){
    if(original_interrupt_function!= NULL){
        original_interrupt_function(execute_data);
    }}PHP_MINIT_FUNCTION(my_extension){
    original_interrupt_function = zend_interrupt_function;
    zend_interrupt_function = my_interrupt_function;

    return SUCCESS;}

##替换操作码处理程序

TODO

The above is the detailed content of PHP hooks. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools