I work on a payments backend, so I spend more time than I'd like thinking about what ends up in our logs. Usually the suspect is someone doing Log::info($request->all()). But there's a quieter way for a card number to get there: a completely normal TypeError in a constructor.
Small disclosure first: I maintain an open-source DTO library, and at the end I show how it handles this. Everything before that is plain PHP, so it applies no matter what you use.
Reproducing it
<?php
declare(strict_types=1);
final class PaymentData
{
public function __construct(
public readonly int $amount,
public readonly string $cardNumber,
) {}
}
function handle(array $input): PaymentData
{
return new PaymentData($input['amount'], $input['card_number']);
}
try {
handle(['amount' => '1500', 'card_number' => '4111111111111111']);
} catch (TypeError $e) {
echo $e->getMessage(), "\n\n", $e->getTraceAsString(), "\n";
}
Nothing special here. amount came in as a string, which happens all the time with forms, CSV files and partner APIs. Now run it with php -n demo.php:
PaymentData::__construct(): Argument #1 ($amount) must be of type int, string given, called in demo.php on line 14
#0 demo.php(14): PaymentData->__construct('1500', '411111111111111...')
#1 demo.php(18): handle(Array)
#2 {main}
The error is about amount, but look at frame #0. All the constructor arguments are there, card number included. getTraceAsString() cuts strings to 15 chars (that's zend.exception_string_param_max_len), so you get 15 of 16 digits. Not great. And if something reads $e->getTrace() directly (some error tracking SDKs do this to show function arguments), it gets the full value:
var_dump($e->getTrace()[0]['args'][1]); // string(16) "4111111111111111"
"We have exception_ignore_args in prod, so we're fine"
Maybe. php.ini-production sets zend.exception_ignore_args = On, and then the same trace shows PaymentData->__construct() with empty parentheses. But:
- If no php.ini is loaded, the default is Off. The official
phpDocker images shipphp.ini-productionandphp.ini-developmentside by side, but don't load either of them. If your Dockerfile never copies one or sets the option, you're running with Off. - It only hides arguments. Exception messages are a different story.
So check what you actually have. And check it in the process that serves traffic, because CLI and FPM can read different ini files:
var_dump(ini_get('zend.exception_ignore_args')); // want "1"
Messages leak too
Some exceptions put the bad value right into the message. And messages get logged no matter what you set for trace arguments. Two common ones (output from PHP 8.3):
enum Currency: string { case UAH = 'UAH'; case EUR = 'EUR'; }
Currency::from('4111 1111 1111 1111');
// ValueError: "4111 1111 1111 1111" is not a valid backing value for enum Currency
new DateTimeImmutable('4111111111111111');
// DateMalformedStringException: Failed to parse time string (4111111111111111) at position 8 (1): Double date specification
Of course nobody types a card number into a currency field. But columns get shifted, a partner swaps two fields, a CSV loses a delimiter. And then the value that fails to cast is exactly the one you didn't want to see in your error tracker.
What you can do in plain PHP
1. Turn on zend.exception_ignore_args in every production image. Set it explicitly, don't rely on defaults, and check it in a smoke test after deploy. It's the cheapest fix and it covers all frames at once.
2. Use #[\SensitiveParameter] (PHP 8.2+). If you mark a parameter, PHP puts a SensitiveParameterValue object in the trace instead of the value:
final class PaymentData
{
public function __construct(
public readonly int $amount,
#[\SensitiveParameter] public readonly string $cardNumber,
) {}
}
function handle(#[\SensitiveParameter] array $input): PaymentData { /* ... */ }
#0 demo.php(14): PaymentData->__construct('1500', Object(SensitiveParameterValue))
#1 demo.php(18): handle(Object(SensitiveParameterValue))
The problem is you need it on every parameter of every function the raw payload goes through: controller helper, mapper, factory. Forget one and that frame leaks again. And it doesn't help with messages at all.
3. Don't put values into exception messages. Where you turn input into objects, catch the exception and throw a new one with just the field name, like Invalid value for field 'currency'. And don't pass the original as previous. Most loggers print the whole chain, messages included.
4. Watch dumps and serialization. __debugInfo() changes what var_dump() and print_r() show, but not var_export() or serialize(). And serialize() writes the full value wherever the result goes, like a queued job payload in Redis or in the jobs table, or a cache entry. If an object should never leave the process, __serialize() is the place to scrub it, or just throw there.
What I did in my library
Simple Data Objects builds the constructor call itself, so it can do most of this for you:
- The raw payload is marked
#[\SensitiveParameter]infrom(), in the generated hydrator and in the internal helpers that touch it. - If the constructor throws, the library rewrites the trace before rethrowing. Every argument in the DTO's
__constructframe becomes aSensitiveParameterValue, marked or not. Here's the main part fromsrc/Support/Redactor.php:
foreach ($trace as $i => $frame) {
if (($frame['function'] ?? null) === '__construct'
&& isset($frame['class'], $frame['args'])
&& is_a($class, (string) $frame['class'], true)) {
$trace[$i]['args'] = array_map(
static fn (mixed $arg): \SensitiveParameterValue => $arg instanceof \SensitiveParameterValue ? $arg : new \SensitiveParameterValue($arg),
(array) $frame['args'],
);
}
}
Yes, it writes to the private trace property of Exception and Error through reflection, for every exception in the previous chain. It's a hack, and I'd be happy if PHP didn't need it. But it only runs when something has already failed.
- Messages the library builds go through a card number mask, just as a safety net. Any run of 13 to 19 digits (spaces and dashes are fine) keeps only the last four. So
"4111 1111 1111 1111" is not a valid backing valueturns into"**** **** **** 1111" is not a valid backing value. - If a property has
#[Sensitive]and its cast fails, you get a generic error without the original message. Add theHasSensitiveFieldstrait andvar_dump()shows[redacted], whileserialize()throws instead of writing the value out:
use StdOut\SimpleDataObjects\BaseData;
use StdOut\SimpleDataObjects\Attributes\Sensitive;
use StdOut\SimpleDataObjects\Concerns\HasSensitiveFields;
final class PaymentData extends BaseData
{
use HasSensitiveFields;
public function __construct(
public readonly int $amount,
#[Sensitive]
public readonly string $cardNumber,
) {}
}
It's not magic though. The mask only catches things that look like card numbers, not CVVs, IBANs, tokens or passwords. #[Sensitive] and the trait are opt-in. And if you log $request->all() yourself, no library will save you. This closes the accidental paths, nothing more.
And a nice bonus on top of all this: the library is fast and easy on resources. Each DTO class gets its hydrator and serializer compiled once, so there's no reflection work on every call, and lazyCollection() keeps memory flat on large imports. I'm leaving numbers out on purpose, because this post is about logs. If you're curious, the benchmark repo lets you measure it on your own payloads.
The library is std-out/simple-data-objects (PHP 8.4+, MIT).
Quick checklist
-
ini_get('zend.exception_ignore_args')returns"1"in FPM or your workers, not only in CLI. - Your Dockerfile copies
php.ini-productionor sets the option itself. - Functions and constructors that get raw card data or credentials use
#[\SensitiveParameter]. - Boundary code throws with field names, not values, and doesn't chain the original exception.
- Objects with secrets have
__debugInfo()and scrub or block__serialize(). - Grep a day of logs for runs of 13 to 19 digits. Crude, but even one real hit is worth a ticket.
What did I miss? If you've caught sensitive data leaking into logs somewhere unexpected, I'd really like to hear where.
Top comments (4)
Yurii, the detail that makes this land is the 15-of-16-digits one — getTraceAsString() looks like it redacts, but it is only truncating, and anyone reading getTrace() directly gets the full number. That is the kind of almost-safe that survives code review.
The Docker-image point is the one I would check first in my own setup: php.ini-production exists in the image, so it feels configured, but nothing loads it, and CLI and FPM can quietly disagree. Your checklist line about checking ini_get('zend.exception_ignore_args') in FPM, not just CLI, is the whole post in one line.
The part I would add to the checklist is the error-tracking SDK angle you mention in passing — if an SDK reads getTrace() to show function arguments, the trace leaves your process with the full value, so the fix has to happen before the exception is handed to the SDK, not in the log pipeline after it. Have you run into a case where the leak was in the SDK payload rather than the log file itself, or is that still the gap you would expect to find first when you grep a day of logs?
Thanks.
One detail on the SDK side:
exception_ignore_argsand#[\SensitiveParameter]both work when the exception is created, so by the time any SDK callsgetTrace()the args are already gone or wrapped in SensitiveParameterValue.If neither is in place, a before_send hook is the last place to scrub. And yes, I'd expect the SDK payload to be the bigger gap, because nobody greps their error tracker.
A few more places that sit outside the log file. Laravel's failed_jobs table stores the serialized job payload and the exception trace in their own columns, so both can hold the value even when the log channel is clean. Query listeners and slow-query logging record bound parameters, and a Guzzle client with debug on, or a request-logging middleware, writes request bodies. For error-tracking SDKs, most expose a before-send style hook, and that is where to scrub, because the payload is built from getTrace() before any log processor sees it. I would run the 13 to 19 digit grep against the failed_jobs table and the tracker's stored events as well as a day of log files.
Great list, thanks.
failed_jobs is a nasty one: it keeps the serialized payload and the exception, and they stay there until someone prunes the table.
That's also why
HasSensitiveFieldsthrows on serialize, so a DTO with card data can't quietly end up in a queue payload.Agree on grepping the tracker's stored events too, that's worth adding to the checklist.