Sentry Answers>PHP>

How do I print the call stack in PHP?

How do I print the call stack in PHP?

Richard C.

The ProblemJump To Solution

When an error occurs in PHP and you want to understand the flow of program logic that occurred, it’s useful to be able to print the call stack — all the functions that were called up to this point.

The Solution

Use debug_print_backtrace();.

Below is a simple example PHP script with three functions called in sequence: A, B, and C. Function C prints the call stack:

Click to Copy
<?php A("a"); function A($a) { B(); } function B() { C(); } function C() { debug_print_backtrace(); } ?>

Put this script in a file called test.php and run it with php test.php. The output is:

Click to Copy
#0 /home/user/test.php(10): C() #1 /home/user/test.php(5): B() #2 /home/user/test.php(19): A('a')

This is the fastest way to print the stack trace.

The A('a') indicates the function A received parameters. You probably don’t need to see this, so to make the output neater use: debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);.

To print the full details of every call, including parameter values, use:

Click to Copy

The output will be:

Click to Copy
array(3) { [0]=> array(4) { ["file"]=> string(35) "/home/user/test.php" ["line"]=> int(9) ["function"]=> string(1) "C" ["args"]=> array(0) { } } [1]=> array(4) { ["file"]=> string(35) "/home/user/test.php" ["line"]=> int(5) ["function"]=> string(1) "B" ["args"]=> array(0) { } } [2]=> array(4) { ["file"]=> string(35) "/home/user/test.php" ["line"]=> int(2) ["function"]=> string(1) "A" ["args"]=> array(1) { [0]=> string(1) "a" } } }

To ignore function arguments, you can use var_dump(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));.

Use An Exception Trace To Reduce Memory Use

Some users on StackOverflow and the PHP manual website say that backtrace can cause memory problems with very large applications. If you encounter this, you could instead try printing the call stack with:

Click to Copy
$e = new Exception(); var_dump($e->getTraceAsString());

Further Reading

  • logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.


Loved by over 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.