du9698 2018-04-10 18:28
浏览 671
已采纳

复制和修改数组

I'm not experienced with PHP and have to redact the password in the following code:

    $body=array(
        'userInfo' => array(
            'userName' => $username,
            'password' => $password,
            'applicationKey' => $appKey,
        ),
    );

The variable $body is used both in application logic, and in logging the array:

$this->logger->debug("REQUEST: URL[{$this->config->endpoint}] BODY: " . json_encode($body));

But I should not be logging the password. I'd like to redact it.

I know I could just copy and paste the array to a new variable $body_with_password_hidden but I'd like to learn some PHP idioms, not to mention keep the code base as compact as realistically possible.

What would be an elegant way to do this? In a language I am more comfortable, I would clone the dictionary, and overwrite the sensitive value. How would I do this in PHP?

More info

Current log statement:

[2018-04-10T18:23:11+00:00] [DEBUG] REQUEST: URL[http://myservice.com/myendpoint/login] BODY: {"userInfo":{"userName":"Administrator","password":"Administrator","applicationKey":"abc123"}} -

Desired log statement:

[2018-04-10T18:23:11+00:00] [DEBUG] REQUEST: URL[http://myservice.com/myendpoint/login] BODY: {"userInfo":{"userName":"Administrator","password":"********","applicationKey":"abc123"}} -
  • 写回答

5条回答 默认 最新

  • dqd78456 2018-04-10 18:49
    关注

    You can create a template that matches the structure of your data, with your desired redaction symbol as a value for the appropriate key.

    $redacted = ['userInfo' => ['password' => '********']];
    

    Then use array_replace_recursive to overwrite the value in the original data when you log it.

    $this->logger->debug(
        "REQUEST: URL[{$this->config->endpoint}] BODY: "
        . json_encode(array_replace_recursive($body, $redacted))
    );
    

    This may be kind of overkill for overwriting a single value, but could be a neater way of doing it if you ever have a more complex structure with more values that need to be replaced.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。