• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

🔒 The `#[SensitiveParameter]` Attribute in PHP 8.2+

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,605
Баллы
155


During debugging and error monitoring, it's common for stack traces to be recorded in logs. However, these traces can accidentally capture and expose critical data, such as passwords, API tokens, or credit card numbers.

PHP 8.2 solves this problem with the introduction of the #[SensitiveParameter] attribute.

What is #[SensitiveParameter]?


#[SensitiveParameter] is a metadata attribute you can apply to a specific parameter of a function or method.

If an exception or error is thrown inside the function, PHP ensures that the value of this marked parameter will not be included in the generated stack trace. Instead of the real value, the log will display a secure placeholder, such as *** or *sensitive*.

Goal: To prevent the accidental exposure of confidential data in production logs, crash reports, or detailed error messages, thus strengthening application security.

💡 Practical Demonstration


Consider a simple authentication method that throws an exception if the credentials are invalid.

1. The Old Scenario (PHP < 8.2)


Without the attribute, if the method fails, the stack trace will show the actual password value:

PHP


function login(string $username, string $password)
{
// Authentication attempt...
if (false) { // Simulates a failure
// Stack trace would include: login('user@email.com', 'my_secret_password')
throw new Exception("Failed to authenticate user.");
}
}

try {
login('user@email.com', 'my_secret_password');
} catch (Exception $e) {
// $e->getTraceAsString() exposes 'my_secret_password'
// ...
}




2. The Secure Scenario (PHP 8.2+)


By applying the attribute to the $password parameter, we ensure it will be masked:

PHP


use SensitiveParameter; // Import the attribute (or use \SensitiveParameter)

function login(
string $username,
#[SensitiveParameter] string $password // Marks the parameter as sensitive
) {
// Authentication attempt...
if (false) { // Simulates a failure
// Stack trace will include: login('user@email.com', Object(SensitiveParameterValue))
// The actual value is replaced by a secure object in the trace
throw new Exception("Failed to authenticate user.");
}
}

try {
login('user@email.com', 'my_secret_password');
} catch (Exception $e) {
// The stack trace generated by PHP or logging tools
// (like Monolog or Sentry) will NOT display the string 'my_secret_password'.
// ...
}





In the log, the sensitive argument will be visually represented as Object(SensitiveParameterValue), protecting the data.


The #[SensitiveParameter] is a small yet powerful addition to PHP 8.2 that reflects the language's ongoing focus on building robust and secure applications. It is an essential feature for any project that handles authentication data or private keys.



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу