


[Translation] [php extension development and embedded] Chapter 16 - Interesting Flow
Interesting Streams
One feature that is often mentioned in PHP is the stream context. This is optional The parameters are even available in most stream creation related functions in user space, and it serves as a generalized framework for passing additional information to/from a given wrapper or stream implementation.
Context
The context of each stream contains two internal message types. The first and most commonly used are the context options. These values are arranged in the context In a two-dimensional array, it is usually used to change the initialization behavior of the flow wrapper. There is also a context parameter, which is unknown to the wrapper. Currently, it provides a way for event notification inside the flow wrapper layer. .
php_stream_context *php_stream_context_alloc(void);
A context can be created through this API call, which will allocate some storage space and initialize a HashTable for saving context options and parameters. It will also automatically register as a request termination Resources that will be cleaned up later.
Set options
Internal API and user space API for setting context options are equivalent:
int php_stream_context_set_option(php_stream_context *context, const char *wrappername, const char *optionname, zval *optionvalue);
The following is the user space prototype:
bool stream_context_set_option(resource $context, string $wrapper, string $optionname, mixed $value);
The only difference between them is the data type required in user space and internally. The following example uses these two API calls to initiate an HTTP request through the built-in wrapper and overrides user_agent through a context option. Settings.
php_stream *php_varstream_get_homepage(const char *alt_user_agent TSRMLS_DC) { php_stream_context *context; zval tmpval; context = php_stream_context_alloc(TSRMLS_C); ZVAL_STRING(&tmpval, alt_user_agent, 0); php_stream_context_set_option(context, "http", "user_agent", &tmpval); return php_stream_open_wrapper_ex("http://www.php.net", "rb", REPORT_ERRORS | ENFORCE_SAFE_MODE, NULL, context); }
##In php-5.4.10 used by the translator, php_stream_context_alloc() was added Thread safety control has been implemented, so the example has been modified accordingly. Please pay attention when testing.
It should be noted here that tmpval does not allocate any persistence. The storage space, its string value is set by copying. php_stream_context_set_option() will automatically copy the incoming zval content.
Get Return options
#The API call used to retrieve context options is exactly the mirror image of the corresponding settings API:
int php_stream_context_get_option(php_stream_context *context, const char *wrappername, const char *optionname, zval ***optionvalue);
Review the previous , the context options are stored in a nested HashTable. When retrieving a value from a HashTable, the general method is to pass a pointer to zval ** to zend_hash_find(). Of course, since php_stream_context_get_option() is zend_hash_find() A special agent, their semantics are the same.
The following is a simplified example of using the built-in http wrapper to set user_agent using php_stream_context_get_option():
zval **ua_zval; char *user_agent = "PHP/5.1.0"; if (context && php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS && Z_TYPE_PP(ua_zval) == IS_STRING) { user_agent = Z_STRVAL_PP(ua_zval); }
In this case, non-string values will be discarded, because numeric values are meaningless for user-agent strings. Other context options, such as max_redirects, require numeric values, because in character Storing numeric values in string zvals is not universal, so a type conversion needs to be performed to make the setting legal.
不幸的是这些变量是上下文拥有的, 因此它们不能直接转换; 而需要首先进行隔离再进行转换, 最终如果需要还要进行销毁:
long max_redirects = 20; zval **tmpzval; if (context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) { if (Z_TYPE_PP(tmpzval) == IS_LONG) { max_redirects = Z_LVAL_PP(tmpzval); } else { zval copyval = **tmpzval; zval_copy_ctor(©val); convert_to_long(©val); max_redirects = Z_LVAL(copyval); zval_dtor(©val); } }
实际上, 在这个例子中, zval_dtor()并不是必须的. IS_LONG的变量并不需要zval容器之外的存储空间, 因此zval_dtor()实际上不会有真正的操作. 在这个例子中包含它是为了完整性考虑, 对于字符串, 数组, 对象, 资源以及未来可能的其他类型, 就需要这个调用了.
参数
虽然用户空间API中看起来参数和上下文选项是类似的, 但实际上在语言内部的php_stream_context结构体中它们被定义为不同的成员.
目前只支持一个上下文参数: 通知器. php_stream_context结构体中的这个元素可以指向下面的php_stream_notifier结构体:
typedef struct { php_stream_notification_func func; void (*dtor)(php_stream_notifier *notifier); void *ptr; int mask; size_t progress, progress_max; } php_stream_notifier;
当将一个php_stream_notifier结构体赋值给context->notifier时, 它将提供一个回调函数func, 在特定的流上发生下表中的PHP_STREAM_NOTIFY_*代码表示的事件时被触发. 每个事件将会对应下面第二张表中的PHP_STREAM_NOTIFY_SEVERITY_*的级别:
事件代码 |
含义 |
RESOLVE |
主机地址解析完成.多数基于套接字的包装器将在连接之前执行这个查询. |
CONNECT |
套接字流连接到远程资源完成. |
AUTH_REQUIRED |
The requested resource is not available,The reason is access control and missing authorization |
MIME_TYPE_IS |
#mime-type of the remote resource is not available |
FILE_SIZE_IS |
Current available size of remote resources |
##REDIRECTED |
##Original URL Request results in redirect to other location |
PROGRESS
|
Due to the transmission of additional data, the php_stream_notifier structure's progress and (Possible)progress_max element is updated(Progress information,Please refer to phpmanualcurl_setopt#CURLOPT_PROGRESSFUNCTION and CURLOPT_NOPROGRESSOptions) |
COMPLETED |
No more data available on the stream |
FAILURE |
##RequestedURL The resource was unsuccessful or incomplete |
AUTH_RESULT |
The remote system has processed the authorization authentication |
security code |
|
#INFO |
Information update.Equivalent to a E_NOTICEError |
WARN |
Minor error condition.Equivalent to an E_WARNINGError |
##ERR
|
Interrupt Error Condition .Equivalent to an E_ERRORError. |

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.