Stack traces
suggest changeA stack trace (also called a backtrace) is the list of function calls that were active at a given moment: which function was running, who called it, who called that one, and so on up to the main script. When something goes wrong, the stack trace tells you not only where it went wrong but how the program got there.
PHP gives you stack traces in several places:
- every exception and error object (
Throwable) records a trace when it is created debug_backtrace()anddebug_print_backtrace()return the current trace at any point- since PHP 8.5, fatal errors such as running out of memory also print a trace
This article shows how to read traces, how to get them in code, how to control what they contain (and keep passwords out of them), and how to log them. All examples were run with PHP 8.5. In the outputs, paths are shortened to /app/.
For the basics of try / catch see Exception and Error handling.
Reading a stack trace
Here's a small program with a bug: one of the items has no price.
<?php
class OrderService
{
public function place(int $orderId, array $items): void
{
$total = $this->total($items);
echo "total: $total\n";
}
private function total(array $items): float
{
return array_sum(array_map(fn($i) => price($i), $items));
}
}
function price(string $sku): float
{
$prices = ['apple' => 0.5, 'pear' => 0.75];
return $prices[$sku] ?? throw new InvalidArgumentException("unknown sku: $sku");
}
$service = new OrderService();
$service->place(42, ['apple', 'banana']);
The exception is never caught, so PHP prints it and stops with exit code 255:
Fatal error: Uncaught InvalidArgumentException: unknown sku: banana in /app/uncaught.php:19
Stack trace:
#0 /app/uncaught.php(12): price('banana')
#1 [internal function]: OrderService->{closure:OrderService::total():12}('banana')
#2 /app/uncaught.php(12): array_map(Object(Closure), Array)
#3 /app/uncaught.php(6): OrderService->total(Array)
#4 /app/uncaught.php(23): OrderService->place(42, Array)
#5 {main}
thrown in /app/uncaught.php on line 19
How to read it:
- The first line has the exception class, the message, and the file and line where the exception was created (
uncaught.php:19, insideprice()). - Frame
#0is the innermost call./app/uncaught.php(12): price('banana')means: "on line 12,price()was called with the argument'banana'". The file and line are the call site, not the place inside the called function. - Each following frame is one level further out, up to
{main}, the top-level code of the script. Class->methodis an instance method call,Class::methodis a static call.[internal function]means the call was made by PHP itself, not by your code. Herearray_map()called the closure.- Closures are named after where they are defined. Since PHP 8.4 that's
{closure:OrderService::total():12}(the closure on line 12 insidetotal()) or{closure:/path/file.php:21}for a closure at the top level. Older versions just print{closure}. - Arguments are shown in a short form: strings are cut at 15 characters, arrays print as
Arrayand objects asObject(ClassName).
Read a trace from the top to find where the error happened, and down to find which of your calls led there. The most useful frame is often the first one that points into your own code rather than a library.
Getting the trace from an exception
Every Throwable has these methods:
getFile()andgetLine(): where the exception was createdgetTrace(): the trace as an array of framesgetTraceAsString(): the trace formatted like in the output above
<?php
class Repo
{
public function find(int $id): array
{
throw new RuntimeException("row $id not found");
}
}
function loadUser(Repo $repo, int $id): array
{
return $repo->find($id);
}
try {
loadUser(new Repo(), 7);
} catch (RuntimeException $e) {
echo $e->getMessage(), "\n";
echo $e->getFile(), ':', $e->getLine(), "\n\n";
echo $e->getTraceAsString(), "\n\n";
print_r($e->getTrace());
}
Output:
row 7 not found
/app/gettrace.php:6
#0 /app/gettrace.php(12): Repo->find(7)
#1 /app/gettrace.php(16): loadUser(Object(Repo), 7)
#2 {main}
Array
(
[0] => Array
(
[file] => /app/gettrace.php
[line] => 12
[function] => find
[class] => Repo
[type] => ->
[args] => Array
(
[0] => 7
)
)
[1] => Array
(
[file] => /app/gettrace.php
[line] => 16
[function] => loadUser
[args] => Array
(
[0] => Repo Object
(
)
[1] => 7
)
)
)
Each frame is an array with these keys:
| Key | Meaning |
|---|---|
function |
name of the called function or method |
class |
class name, only for method calls |
type |
-> for an instance call, :: for a static call |
file, line |
where the call was made; missing for calls made by PHP internally |
args |
the actual argument values; missing when arguments are disabled (see below) |
Two things to note:
- The place where the exception was created (
gettrace.php:6) is not a frame ingetTrace(). You get it fromgetFile()andgetLine(). {main}is only added bygetTraceAsString(). It isn't in the array.
Converting a Throwable to a string (echo $e, (string) $e, string interpolation) gives you everything at once: class, message, location and trace, plus the chain of previous exceptions:
<?php
function parsePort(string $s): int
{
return intdiv(100, (int) $s);
}
try {
parsePort('zero');
} catch (DivisionByZeroError $e) {
echo $e, "\n";
}
Output:
DivisionByZeroError: Division by zero in /app/tostring.php:4
Stack trace:
#0 /app/tostring.php(4): intdiv(100, 0)
#1 /app/tostring.php(8): parsePort('zero')
#2 {main}
This is the easiest thing to put in a log message.
The trace is captured when the exception is created
The trace and the line number are recorded by the constructor, when you write new SomeException, not by throw. Usually both happen on the same line, so the difference doesn't matter. It does matter with a factory function:
<?php
function makeError(string $msg): RuntimeException
{
return new RuntimeException($msg); // trace is captured here
}
function check(int $n): void
{
if ($n < 0) {
throw makeError("negative: $n"); // not here
}
}
try {
check(-1);
} catch (RuntimeException $e) {
echo "line: ", $e->getLine(), "\n";
echo $e->getTraceAsString(), "\n";
}
Output:
line: 4
#0 /app/created.php(10): makeError('negative: -1')
#1 /app/created.php(15): check(-1)
#2 {main}
The reported line is 4, inside makeError(), and the factory shows up as an extra frame. The trace is still useful, because frame #0 points at the real throw on line 10. Named constructors on the exception class itself (ConfigException::unreadable(...), see Custom errors) behave the same way.
It also means that re-throwing the same object keeps the original trace:
<?php
function inner(): void
{
throw new LogicException('boom');
}
function outer(): void
{
try {
inner();
} catch (LogicException $e) {
echo "logging and rethrowing\n";
throw $e; // same object, original trace is kept
}
}
try {
outer();
} catch (LogicException $e) {
echo "thrown at line ", $e->getLine(), "\n";
echo $e->getTraceAsString(), "\n";
}
Output:
logging and rethrowing
thrown at line 4
#0 /app/rethrow.php(10): inner()
#1 /app/rethrow.php(18): outer()
#2 {main}
So throw $e; loses nothing. If you wrap the exception in a new one instead, always pass the original as $previous, otherwise its trace is gone.
A trace without an exception
Sometimes you want to know how the program got to a certain point without anything failing. Use debug_print_backtrace() to print the current trace, or debug_backtrace() to get it as an array with the same keys as getTrace():
<?php
class Mailer
{
public function send(string $to, string $subject): void
{
debug_print_backtrace();
echo "---\n";
foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $i => $frame) {
printf("#%d %s%s%s() called at line %d\n",
$i,
$frame['class'] ?? '',
$frame['type'] ?? '',
$frame['function'],
$frame['line'] ?? 0);
}
}
}
function notify(Mailer $m, string $user): void
{
$m->send("$user@example.com", 'Welcome');
}
notify(new Mailer(), 'alice');
Output:
#0 /app/dbt.php(21): Mailer->send('alice@example.c...', 'Welcome')
#1 /app/dbt.php(24): notify(Object(Mailer), 'alice')
---
#0 Mailer->send() called at line 21
#1 notify() called at line 24
debug_backtrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT, int $limit = 0) takes two optional arguments:
DEBUG_BACKTRACE_IGNORE_ARGSleaves out theargskey. Use it unless you need the arguments: it's cheaper and you don't accidentally keep large objects alive.DEBUG_BACKTRACE_PROVIDE_OBJECT(the default) adds anobjectkey with the$thisof each method call.$limitstops after that many frames. If you only need your caller, ask for 2 or 3 frames instead of the whole stack.
Options can be combined with |, and debug_print_backtrace() accepts DEBUG_BACKTRACE_IGNORE_ARGS and a limit too.
Another quick trick is creating an exception just to get its formatted trace, without throwing it:
<?php
function cacheGet(string $key): ?string
{
// log where unexpected cache misses come from
error_log("cache miss for $key\n" . (new Exception())->getTraceAsString());
return null;
}
function productPage(int $id): void
{
cacheGet("product:$id");
}
productPage(5);
Output (on stderr):
cache miss for product:5
#0 /app/here.php(11): cacheGet('product:5')
#1 /app/here.php(14): productPage(5)
#2 {main}
Finding out who called a function
A common use of debug_backtrace() is reporting the caller of a function, for example in a deprecation warning. Frame [1] is the call to the current function, so its file and line are the call site. Frame [2], if it exists, is the function containing that call site:
<?php
// Returns "function() at file:line" for whoever called the current function.
function caller(): string
{
// [0] the call to caller()
// [1] the call to the current function: its file and line are the call site
// [2] the function that contains that call site (missing at top level)
$bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
$site = $bt[1] ?? null;
if ($site === null) {
return 'unknown';
}
$f = $bt[2] ?? null;
$fn = $f ? ($f['class'] ?? '') . ($f['type'] ?? '') . $f['function'] . '()' : '{main}';
return sprintf('%s at %s:%d', $fn, basename($site['file']), $site['line']);
}
function legacyFormat(float $n): string
{
trigger_error('legacyFormat() is deprecated, called from ' . caller(), E_USER_DEPRECATED);
return number_format($n, 2);
}
class Report
{
public function build(): string
{
return legacyFormat(1234.5);
}
}
echo (new Report())->build(), "\n";
echo legacyFormat(99), "\n";
Output:
Deprecated: legacyFormat() is deprecated, called from Report->build() at caller.php:28 in /app/caller.php on line 20
1,234.50
Deprecated: legacyFormat() is deprecated, called from {main} at caller.php:33 in /app/caller.php on line 20
99.00
The warning itself points at line 20, inside legacyFormat(), which isn't helpful. The caller information tells the user which line of their code to change.
Don't use debug_backtrace() for program logic, such as behaving differently depending on who called you. It's slow compared to a normal function call, and it makes code fragile: refactoring a caller changes the behavior.
Arguments in traces
Arguments in traces are very useful for debugging, but they can be a problem:
- they may contain secrets: passwords, API keys, tokens
- they keep the argument values alive as long as the exception object exists
PHP has three ways to control this.
#[\SensitiveParameter]
Since PHP 8.2, mark parameters that hold secrets with the #[\SensitiveParameter] attribute. In traces, their value is replaced by a SensitiveParameterValue object:
<?php
function connect(string $dsn, string $user, #[\SensitiveParameter] string $password): void
{
throw new RuntimeException('connection refused');
}
try {
connect('pgsql:host=db.internal;dbname=shop', 'shop', 'hunter2-secret');
} catch (RuntimeException $e) {
echo $e->getTraceAsString(), "\n";
var_dump($e->getTrace()[0]['args']);
}
Output:
#0 /app/args.php(8): connect('pgsql:host=db.i...', 'shop', Object(SensitiveParameterValue))
#1 {main}
array(3) {
[0]=>
string(34) "pgsql:host=db.internal;dbname=shop"
[1]=>
string(4) "shop"
[2]=>
object(SensitiveParameterValue)#2 (0) {
}
}
The password doesn't appear in the string form or in the array. Built-in functions that take passwords, like password_hash() and the PDO constructor, already mark their parameters this way.
Note that getTraceAsString() cut the DSN at 15 characters but getTrace() has the full value. If you log print_r($e->getTrace()) or json_encode() it, you log full argument values, so mark sensitive parameters even if the short form looks harmless.
zend.exception_string_param_max_len
The 15-character limit on strings in getTraceAsString() is controlled by the zend.exception_string_param_max_len ini setting (0 to 1000000, default 15). Raise it to see more:
$ php -d zend.exception_string_param_max_len=40 args.php
Output:
#0 /app/args.php(8): connect('pgsql:host=db.internal;dbname=shop', 'shop', Object(SensitiveParameterValue))
#1 {main}
zend.exception_ignore_args
With zend.exception_ignore_args=On, exceptions don't record arguments at all:
$ php -d zend.exception_ignore_args=1 args.php
Output:
#0 /app/args.php(8): connect()
#1 {main}
Warning: Undefined array key "args" in /app/args.php on line 11
NULL
The args key is missing, so code that reads it must use $frame['args'] ?? [].
The built-in default is Off, but the php.ini-production file that ships with PHP (and that most Docker images and distributions use) sets it to On. That's why traces from production often show connect() with no arguments while the same error on your machine shows them. It's a good default: no secrets in logs, and less memory used. It only affects exceptions; debug_backtrace() still returns arguments unless you pass DEBUG_BACKTRACE_IGNORE_ARGS.
Warnings and notices don't have traces
Warnings like "Undefined array key" are reported with only a file and a line. That line is often in a helper function called from many places, so it doesn't say much. Convert warnings to ErrorException with an error handler and they get a full trace:
<?php
set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
if (!(error_reporting() & $severity)) {
return false; // silenced with @ or not reported
}
throw new ErrorException($message, 0, $severity, $file, $line);
});
function readSetting(array $config, string $key): string
{
return $config[$key]; // warning for a missing key
}
function boot(): void
{
$config = ['env' => 'prod'];
echo readSetting($config, 'region'), "\n";
}
try {
boot();
} catch (ErrorException $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
echo $e->getTraceAsString(), "\n";
}
Output:
ErrorException: Undefined array key "region"
#0 /app/warning.php(11): {closure:/app/warning.php:2}(2, 'Undefined array...', '/app/warning.ph...', 11)
#1 /app/warning.php(17): readSetting(Array, 'region')
#2 /app/warning.php(21): boot()
#3 {main}
Frame #0 is the error handler itself, called by PHP at the point of the warning. Frame #1 shows that boot() asked for the 'region' key. Most frameworks install a handler like this by default.
Fatal errors have traces in PHP 8.5
Some errors are not exceptions and can't be caught: running out of memory, exceeding the time limit, and a few others. Before PHP 8.5 they were reported with only a file and line. PHP 8.5 adds a stack trace, controlled by the fatal_error_backtraces ini setting, which is On by default:
<?php
ini_set('memory_limit', '8M');
function loadAll(): array
{
$rows = [];
while (true) {
$rows[] = buildRow(count($rows));
}
}
function buildRow(int $i): string
{
return str_repeat('x', 1024);
}
loadAll();
Output:
Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 20480 bytes) in /app/fatal.php on line 14
Stack trace:
#0 /app/fatal.php(14): str_repeat('x', 1024)
#1 /app/fatal.php(8): buildRow(5856)
#2 /app/fatal.php(17): loadAll()
#3 {main}
Line 14 is just where the last allocation happened to fail. The trace shows the real culprit: the endless loop in loadAll(). With -d fatal_error_backtraces=0 you get only the first line, as in older versions.
The trace is also available in a shutdown function, through a new trace key in the array returned by error_get_last():
<?php
ini_set('display_errors', '0');
set_time_limit(1);
register_shutdown_function(function (): void {
$err = error_get_last();
if ($err === null || !($err['type'] & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR))) {
return;
}
echo "fatal: {$err['message']} at line {$err['line']}\n";
foreach ($err['trace'] ?? [] as $i => $f) {
echo " #$i {$f['function']}() called at line {$f['line']}\n";
}
});
function spin(): void
{
while (true) {}
}
function handle(): void
{
spin();
}
handle();
Output:
fatal: Maximum execution time of 1 second exceeded at line 18
#0 spin() called at line 23
#1 handle() called at line 26
Use ?? [] so the code also works on older PHP versions. See Logging fatal errors for more on shutdown functions.
Logging traces in a custom format
The default format is fine for humans, but you may want something more compact, relative paths, or the chain of previous exceptions in the order "outer first". Build it from getTrace():
<?php
function formatTrace(Throwable $e, string $root): string
{
$out = [];
// the frame where the exception was created is not in getTrace()
$out[] = sprintf(' at %s:%d', str_replace($root, '', $e->getFile()), $e->getLine());
foreach ($e->getTrace() as $f) {
$fn = ($f['class'] ?? '') . ($f['type'] ?? '') . $f['function'] . '()';
$where = isset($f['file'])
? str_replace($root, '', $f['file']) . ':' . $f['line']
: '[internal]';
$out[] = sprintf(' %-28s %s', $fn, $where);
}
return implode("\n", $out);
}
function formatThrowable(Throwable $e, string $root): string
{
$parts = [];
for ($cur = $e; $cur !== null; $cur = $cur->getPrevious()) {
$label = $cur === $e ? '' : 'Caused by: ';
$parts[] = $label . $cur::class . ': ' . $cur->getMessage() . "\n" . formatTrace($cur, $root);
}
return implode("\n", $parts);
}
class PaymentException extends RuntimeException {}
class Gateway
{
public function charge(int $cents): void
{
throw new RuntimeException('HTTP 503 from payments API');
}
}
class Checkout
{
public function __construct(private Gateway $gw) {}
public function pay(int $cents): void
{
try {
$this->gw->charge($cents);
} catch (RuntimeException $e) {
throw new PaymentException("payment of $cents failed", previous: $e);
}
}
}
set_exception_handler(function (Throwable $e): void {
$text = formatThrowable($e, __DIR__ . DIRECTORY_SEPARATOR);
error_log($text); // goes to the server log / stderr
echo "Something went wrong. We've been notified.\n";
});
(new Checkout(new Gateway()))->pay(1999);
The user sees only:
Something went wrong. We've been notified.
The log (stderr in the CLI) gets:
PaymentException: payment of 1999 failed
at format.php:46
Checkout->pay() format.php:57
Caused by: RuntimeException: HTTP 503 from payments API
at format.php:33
Gateway->charge() format.php:44
Checkout->pay() format.php:57
Notes:
- The handler uses
isset($f['file'])and?? ''because not every frame has every key. - It doesn't use
args, so it works the same withzend.exception_ignore_argson or off, and never leaks argument values. - Never show traces to users of a web application. They reveal file paths, code structure and possibly data. Log them, and show a generic message. See Setting error reporting and where to display them.
Logging libraries like Monolog do this for you: pass the exception in the context ($logger->error('payment failed', ['exception' => $e])) and the formatter includes the trace and the previous exceptions.
Xdebug
With the Xdebug extension installed in develop mode, PHP's error messages get richer traces: a table with time and memory per frame, and optionally the values of local variables (xdebug.show_local_vars=1). Xdebug also adds xdebug_get_function_stack(), a more detailed version of debug_backtrace(). Use it in development only; it slows PHP down considerably.
Summary
- Read traces from the top: frame
#0is the innermost call. Each frame shows the call site (file and line) and the function that was called. - Get a trace from any
ThrowablewithgetTraceAsString(),getTrace()or by converting it to a string. The creation point is ingetFile()/getLine(), not in the frames. - Traces are captured by
new, not bythrow. Re-throwing the same object keeps its trace; wrapping requires$previous. - Use
debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $limit)ordebug_print_backtrace()to get a trace without an exception. - Mark secrets with
#[\SensitiveParameter]. Production configs usually setzend.exception_ignore_args=On, so don't rely onargs. - Convert warnings to
ErrorExceptionto get traces for them. - PHP 8.5 prints traces for fatal errors and adds
tracetoerror_get_last(). - Log traces, never show them to users.