Hide sensitive parameter values with the SensitiveParameter PHP attribute

Published on 2024-08-15 • Modified on 2024-08-15

This snippet shows how to hide sensitive parameter values with the SensitiveParameter PHP attribute. PHP 8.2 introduced this parameter. Thanks to it, in the log, instead of having the actual value of the function parameter (here "fooBar123"), we get a SensitiveParameterValue object not containing the actual value.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet313Trait
{
    public function snippet313(): void
    {
        $this->useSensitiveParameter('fooBar123');

        // That's it! 😁
    }

    private function useSensitiveParameter(#[\SensitiveParameter] string $sensitiveParameter): void
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1);
        $arg = $trace[0]['args'][0] ?? null;

        echo 'raw parameter: '.$sensitiveParameter.PHP_EOL;
        echo 'masked parameter: '.get_debug_type($arg).PHP_EOL;
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!