Configure Length of Arguments in Stack Trace using PHP 8.0

Debugging is an important part of the software developing which usually requires to work with stack traces. A stack trace is a list of the function and method calls that generated when an exception was thrown.

In PHP, function or method arguments presented in the stack trace have limited length. This means if length of the string that represents arguments exceeds 15 bytes, then string is truncated, followed by an ellipsis (...).

Let’s say we have a function that throws an exception.

<?php

function doSomething(string $str)
{
    try {
        throw new InvalidArgumentException('Invalid argument');
    } catch (Throwable $throwable) {
        echo $throwable;
    }
}

doSomething('ABCDEFGHIJKLMNOPQRSTUVWXYZ');

Exception is caught and printed:

InvalidArgumentException: Invalid argument in main.php:6
Stack trace:
#0 main.php(12): doSomething('ABCDEFGHIJKLMNO...')
#1 {main}

As we can see, length of the function arguments in the stack trace is truncated to 15 bytes. Sometimes that length is not enough to print information such as URLs, paths, etc.

Since PHP 8.0, we can use zend.exception_string_param_max_len directive that allows to configure length of the arguments in the stack trace. For example, this directive can be set in php.ini file or at runtime using ini_set function. Value can be between 0 and 1000000.

zend.exception_string_param_max_len = 20

If we run the code again we will get the following stack trace:

InvalidArgumentException: Invalid argument in main.php:6
Stack trace:
#0 main.php(12): doSomething('ABCDEFGHIJKLMNOPQRST...')
#1 {main}

Length limit of the arguments in the stack trace affect places, where:

  1. Exception is converted to string. For example, echo $throwable.
  2. Stack trace is retrieved as a string. For example, $throwable->getTraceAsString().
  3. Stack trace is printed when an exception is uncaught.

Length limit not affect places, where:

  1. Stack trace is retrieved as an array. For example, $throwable->getTrace().
  2. Stack trace is printed using debug_print_backtrace function.

Leave a Comment

Your email address will not be published. Required fields are marked *