Function name: stream_notification_callback()
Function Description: This function is used to handle callback functions for stream notifications.
Applicable version: PHP 4 >= 4.3.0, PHP 5, PHP 7
Syntax: void stream_notification_callback(int $notification_code, int $severity, string $message, int $message_code, int $bytes_transferred, int $bytes_max)
parameter:
Return value: No return value.
Example:
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { switch ($notification_code) { case STREAM_NOTIFY_CONNECT: echo "连接建立成功!\n"; break; case STREAM_NOTIFY_AUTH_REQUIRED: echo "需要进行身份验证!\n"; break; case STREAM_NOTIFY_AUTH_RESULT: echo "身份验证结果:$message\n"; break; case STREAM_NOTIFY_FILE_SIZE_IS: echo "文件大小:$bytes_max 字节\n"; break; case STREAM_NOTIFY_PROGRESS: echo "已传输字节数:$bytes_transferred / $bytes_max\n"; break; case STREAM_NOTIFY_COMPLETED: echo "传输完成!\n"; break; case STREAM_NOTIFY_FAILURE: echo "传输失败!\n"; break; case STREAM_NOTIFY_RESOLVE: echo "正在解析主机信息...\n"; break; case STREAM_NOTIFY_MIME_TYPE_IS: echo "MIME 类型:$message\n"; break; default: echo "未知通知类型\n"; break; } } $stream_context = stream_context_create(); stream_context_set_params($stream_context, ['notification' => 'stream_notification_callback']); $file = fopen('http://example.com', 'r', false, $stream_context);
In the example above, we define a callback function called stream_notification_callback to handle stream notifications. This function judges different notification types based on the incoming notification_code parameter and performs corresponding processing. When opening a URL resource, we create a stream context through the stream_context_create() function, and then set the notification parameter for the callback function we defined with the stream_context_set_params() function. Finally, we use the fopen() function to open a URL resource, trigger the corresponding notification, and output the corresponding information through the callback function.