PHP 8.2 新特性之 Hide Sensitive Information In The Back Traces

作者: 温新

分类: 【PHP基础】

阅读: 1589

时间: 2023-02-20 15:36:30

hi,我是温新,一名 PHPer

代码遇到错误时需要将错误信息通知到开发人员,通知的这个过程中涉及网络堆栈跟踪发送到第三方服务。在某些情况下,这些堆栈跟踪可能包含敏感信息(例如环境变量、密码或用户名)。于此,PHP 8.2 中新增了 \#[\SensitiveParameter] 属性用于隐藏敏感信息,这样就用担心敏感信息会被堆栈跟踪。

先抛出问题,再来看看新特性的解决方式

<?php

function user (string $name, string $password) 
{
	throw new Exception('Error');	
}

try {
    user('Lucy', 'lucy');
} catch (Exception $e) {
    print_r($e);
}

看看结果

Exception Object
(
    [message:protected] => Error
    [string:Exception:private] => 
    [code:protected] => 0
    [file:protected] => /home/user/scripts/code.php
    [line:protected] => 6
    [trace:Exception:private] => Array
        (
            [0] => Array
                (
                    [file] => /home/user/scripts/code.php
                    [line] => 10
                    [function] => user
                    // 看,输入的参数值被抛出
                    [args] => Array
                        (
                            [0] => Lucy
                            [1] => lucy
                        )

                )
        )

    [previous:Exception:private] => 
)

PHP 8.2 新特性 #[\SensitiveParameter]

<?php

function user (#[\SensitiveParameter] string $name, #[\SensitiveParameter] string $password) 
{
	throw new Exception('Error');	
}

try {
    user('Lucy', 'lucy');
} catch (Exception $e) {
    print_r($e->getTrace());
}
Array
(
    [0] => Array
        (
            [file] => /home/user/scripts/code.php
            [line] => 10
            [function] => user
            // 使用了 #[\SensitiveParameter] 属性
            // 参数值被隐藏            
            [args] => Array
                (
                    [0] => SensitiveParameterValue Object

                    [1] => SensitiveParameterValue Object

                )

        )
)
请登录后再评论