- debug_print_backtrace
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 5 notes
- How to Debug PHP Code (A Very Simple Guide)
- TABLE OF CONTENTS
- PART 1) TURN ON ERROR REPORTING
- PHP ERROR REPORTING MECHANICS
- RECOMMENDED FOR TEST SERVER
- RECOMMENDED FOR LIVE SERVER
- PART 2) COMMON MISTAKES
- FATAL ERRORS – UNDEFINED FUNCTIONS & FILES
- SYNTAX ERRORS – MISSING OPERATORS
- WARNINGS – WRONG DATA TYPE
- NOTICES – NOT REALLY IMPORTANT…
- SILENT ERRORS – WRONG RESULTS
- PART 3) ERROR TRACING & TIPS
- DUMP THE VARIABLES
- STACK TRACE
- MANUAL BREAKPOINT
- CUSTOM ERROR LOG
- USE A GOOD EDITOR OR IDE
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- THE END
debug_print_backtrace
debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval() ed stuff.
Parameters
This parameter is a bitmask for the following options:
DEBUG_BACKTRACE_IGNORE_ARGS | Whether or not to omit the «args» index, and thus all the function/method arguments, to save memory. |
This parameter can be used to limit the number of stack frames printed. By default ( limit = 0 ) it prints all stack frames.
Return Values
Examples
Example #1 debug_print_backtrace() example
function c () debug_print_backtrace ();
>
// test.php file
// this is the file you should run
?php
The above example will output something similar to:
#0 c() called at [/tmp/include.php:10] #1 b() called at [/tmp/include.php:6] #2 a() called at [/tmp/include.php:17] #3 include(/tmp/include.php) called at [/tmp/test.php:3]
See Also
User Contributed Notes 5 notes
Another way to manipulate and print a backtrace, without using output buffering:
// print backtrace, getting rid of repeated absolute path on each file
$e = new Exception ();
print_r ( str_replace ( ‘/path/to/code/’ , » , $e -> getTraceAsString ()));
?>
I like the output of debug_print_backtrace() but I sometimes want it as a string.
bortuzar’s solution to use output buffering is great, but I’d like to factorize that into a function. Doing that however always results in whatever function name I use appearing at the top of the stack which is redundant.
Below is my noddy (simple) solution. If you don’t care for renumbering the call stack, omit the second preg_replace().
function debug_string_backtrace () <
ob_start ();
debug_print_backtrace ();
$trace = ob_get_contents ();
ob_end_clean ();
// Remove first item from backtrace as it’s this function which
// is redundant.
$trace = preg_replace ( ‘/^#0\s+’ . __FUNCTION__ . «[^\n]*\n/» , » , $trace , 1 );
// Renumber backtrace items.
$trace = preg_replace ( ‘/^#(\d+)/me’ , ‘\’#\’ . ($1 — 1)’ , $trace );
If your show your error messages in HTML (with suitable safety using entities), this function won’t work nicely because it uses newlines for formatting.
Here is a function that works similarly, but using tags. Insert it near the beginning of your program to add a stack to Warning output only, or modify it as you like:
// Here is code for error stack output in HTML:
function error_handler_callback($errno,$message,$file,$line,$context)
if ($errno === E_WARNING)
echo «Stack, innermost first:
«.nl2br((new Exception())->getTraceAsString());
return false; // to execute the regular error handler
>
set_error_handler(«error_handler_callback»);
Here’s a function that returns a string with the same information shown in debug_print_backtrace(), with the option to exclude a certain amount of traces (by altering the $traces_to_ignore argument).
I’ve done a couple of tests to ensure that it prints exactly the same information, but I might have missed something.
This solution is a nice workaround to get the debug_print_backtrace() information if you’re already using ob_start() in your PHP code.
function get_debug_print_backtrace ( $traces_to_ignore = 1 ) $traces = debug_backtrace ();
$ret = array();
foreach( $traces as $i => $call ) if ( $i < $traces_to_ignore ) continue;
>
$object = » ;
if (isset( $call [ ‘class’ ])) $object = $call [ ‘class’ ]. $call [ ‘type’ ];
if ( is_array ( $call [ ‘args’ ])) foreach ( $call [ ‘args’ ] as & $arg ) get_arg ( $arg );
>
>
>
$ret [] = ‘#’ . str_pad ( $i — $traces_to_ignore , 3 , ‘ ‘ )
. $object . $call [ ‘function’ ]. ‘(‘ . implode ( ‘, ‘ , $call [ ‘args’ ])
. ‘) called at [‘ . $call [ ‘file’ ]. ‘:’ . $call [ ‘line’ ]. ‘]’ ;
>
function get_arg (& $arg ) if ( is_object ( $arg )) $arr = (array) $arg ;
$args = array();
foreach( $arr as $key => $value ) if ( strpos ( $key , chr ( 0 )) !== false ) $key = » ; // Private variable found
>
$args [] = ‘[‘ . $key . ‘] => ‘ . get_arg ( $value );
>
$arg = get_class ( $arg ) . ‘ Object (‘ . implode ( ‘,’ , $args ). ‘)’ ;
>
>
?>
How to Debug PHP Code (A Very Simple Guide)
Welcome to a tutorial on how to debug PHP code. When it comes to troubleshooting, some beginners foam in the mouth and go into a trance of “very difficult, only for experts”. No. Debugging is a basic skill that does not require any special tools.
- Turning on error reporting.
- Reading the error messages.
- Tracing where the problem is and fixing it.
That’s all, don’t understand what the fuss is all about. Read on for more debugging tips!
TABLE OF CONTENTS
PART 1) TURN ON ERROR REPORTING
The first step of debugging is to stop working in the dark, at least learn how to get the error message.
PHP ERROR REPORTING MECHANICS
When it comes to error reporting in PHP, there are only 3 mechanics:
- error_reporting() – Set the error reporting level. PHP has a long list of error levels, from important E_WARNING to “notice only” E_NOTICE . Will leave a link below to the full list.
- Save the error into a log file.
- log_errors specifies if you want to save the errors into a log file.
- error_log is the target log file.
- display_errors display the error on the screen.
- Don’t confuse this with error_reporting() . Error reporting sets what kinds of errors need to be reported.
- display_errors simply sets if the error should be displayed on the screen.
- That is, we can turn off display_errors but still keep the errors in a log file. But if we turn off error_reporting() , no errors will be reported at all.
RECOMMENDED FOR TEST SERVER
When you are working on your test server, just set PHP to show all errors.
RECOMMENDED FOR LIVE SERVER
- error_reporting(E_ALL & ~E_NOTICE);
- ini_set(«display_errors», 0);
- ini_set(«log_errors», 1);
- ini_set(«error_log», «PATH/error.log»);
Yep, these should be hard-coded into php.ini already. On a live server, we hide the error messages but keep them in a log file. For security purposes, we don’t want to show the error message, and script name to the user.
PART 2) COMMON MISTAKES
Now that you have eyes on an error message, the next step is to make some sense of what it means. Here are some common examples.
FATAL ERRORS – UNDEFINED FUNCTIONS & FILES
Fatal error: Uncaught Error: Call to undefined function doesnotexist() in D:\http\2a-error-fatal.php:2 Stack trace: #0
“Call to undefined function”, what does that mean? If that is not Captain Obvious enough – The function you tried to call is not defined and does not exist. Could be a silly typo mistake, or you forgot to include the file somewhere.
SYNTAX ERRORS – MISSING OPERATORS
“Syntax error on line 3”. Just trace the code back a little, there is a missing ; on line 2. This can also mean a missing ,.()<> somewhere…
WARNINGS – WRONG DATA TYPE
Warnings are not critical errors, but they are still of significant importance. For example, putting a string into a function that seemingly needs numbers instead. While this will not break the system, it may end up with the wrong results.
NOTICES – NOT REALLY IMPORTANT…
An annoying kind of “error”. Notices are often of little importance, and they are just here to remind you of stuff like “you have not defined this variable before”, or “this function has been deprecated, not recommended”.
SILENT ERRORS – WRONG RESULTS
echo add(88, 22); // Should be 110, but result is 66
These are the deadly ones. These errors do not throw any messages, are hard to spot, and the script continues to run “as usual”. You will only realize that there is an error when the scripts do not produce the correct results.
PART 3) ERROR TRACING & TIPS
Some errors are easy to spot. Just go to the script and line that the error message indicates, eyeball a few lines of code. But how do we deal with complicated scripts? Here are a few troubleshooting tips.
DUMP THE VARIABLES
[ "name" => "Foo bar", "qty" => 99 ], "234" => [ "name" => "Doge", "qty" => 88 ] ]; // (C) WHAT'S IN THE CART? print_r($_SESSION); var_dump($_SESSION);
So, what is in an array? What is in the session that may be causing problems? print_r() and var_dump() are your best friends.
STACK TRACE
In big projects, it is common to have multiple scripts sharing many library files. So which scripts and functions were previously called? Use debug_backtrace() and debug_print_backtrace() to find out.
MANUAL BREAKPOINT
// (C) DISPLAY & STOP HERE print_r($varA); echo $varB; exit(); // (D) MORE PROCESSING $varA[] = "Doge"; $varB .= "Last";
With debugging tools, we can set “breakpoints” to pause and check what is in which variables at that point. But no worries, we don’t actually need debugging tools to do that – Just output the variables that you want to check and use die() or exit() to manually stop the script at a specific point.
CUSTOM ERROR LOG
"https://DOES-NOT-EXIST.com/dummy.php", CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false ]); // (B) CURL FETCH $result = curl_exec($curl); if ($result === false) < error_log("Failed connecting to https://DOES-NOT-EXIST.com", 0); >curl_close($curl);
Remember the error log from earlier? Code ninjas can’t be sitting at the desk, monitoring, and waiting for errors to happen 24/7. So utilize the error_log() function to capture your own custom error messages.
USE A GOOD EDITOR OR IDE
Captain Obvious to the rescue! If you have not installed a good code editor, do so now. It helps to automatically indent your code, and highlight all the silly mistakes.
P.S. This is VSCode, and there are plenty of free code editors. Links below.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this guide, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!