PHP 8.5: Stack trace support for PHP Fatal errors
One of the most impactful changes in PHP 7.0 is that it moved several PHP error conditions to throw an Error
exception instead of triggering a fatal error. Type errors, syntax errors, and several other types of errors are exceptions in modern PHP versions.
PHP also supports setting a custom error handler, so certain errors such as deprecation notices, warnings, and other notices can be logged as well.
However, PHP still has certain unrecoverable error conditions that simply show the error message and quit immediately (after calling a shutdown function if there is one set with the register_shutdown_function
function, and it is possible to call it at that stage).
ini_set('memory_limit', '2M');
function my_heavy_function(): void {
$str = str_repeat('A', 1024 * 1024 * 5);
}
my_heavy_function();
The snippet above causes a fatal error because it sets memory_limit
to 2 MiB, and the my_heavy_function()
consumes more memory than the limit.
Prior to PHP 8.5, PHP terminates with this message:
Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 5242912 bytes) in ... on line ...
Although the file name and the line number where the error occurred are mentioned in the error message, it is missing the stack trace. Without a stack trace, it is difficult to trace the stack of callers which lead to that line in the script.
PHP 8.5 adds a new feature so that fatal error messages contain the full stack trace:
Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 5242912 bytes) in /mnt/w/localhost/test/php85/error_handlers.php on line 6
Stack trace:
#0 file.php(...): str_repeat('A', 5242880)
#1 file.php(...): my_heavy_function()
#2 {main}
New fatal_error_backtraces
INI Directive
The new fatal error stack trace is enabled by default, and can be toggled with the new fatal_error_backtraces
INI directive.
For example, to turn off fatal error backtraces, set the INI directive as shown below:
fatal_error_backtraces = Off
Compatibility with other error-handling controls
The new fatal error backtrace feature works together with other INI directives as well.
- With INI
display_errors=Off
, the error messages are now shown on the screen; backtrace is not shown either. - Parameters attributed with
#[\SensitiveParameter]
do not reveal the contents of the arguments passed to that parameter. - With INI
zend.exception_ignore_args
, the backtraces do not contain the arguments passed.
Backward Compatibility Impact
This feature does not introduce any backward-compatibility issues.
Setting INI fatal_error_backtraces = Off
turns off this feature. However, note that turning off the error display with the display_errors=Off
is the recommended way to protect production systems from leaking internal information.