PHP Debugging Techniques – Find & Fix Errors Like a Pro π οΈ
Debugging is like being a detective π΅οΈββοΈβexcept your suspects are missing semicolons, undefined variables, and typos! π§
Here are the best ways to find and fix errors in PHP.
πΉ 1. Displaying Errors with error_reporting()
PHP hides some errors by default. Use error_reporting()
to show them.
π Example: Enabling Error Reporting
<?php error_reporting(E_ALL); ini_set('display_errors', 1); // Intentional mistake: Undefined variable echo $undefinedVar; ?>
Result: This will display a warning about the undefined variable.
πΉ 2. Using var_dump()
for Debugging
The var_dump()
function shows detailed information about a variable.
π Example: Debugging a Variable
<?php $name = "PHP Debugging"; $number = 42; var_dump($name); var_dump($number); ?>
Output: This prints the type and value of each variable.
πΉ 3. Printing Readable Output with print_r()
Use print_r()
to display arrays and objects in a readable format.
π Example: Printing an Array
<?php $fruits = array("Apple", "Banana", "Cherry"); print_r($fruits); ?>
Tip: Use <pre>
tags for better formatting: echo "<pre>"; print_r($array); echo "</pre>";
πΉ 4. Checking Errors with debug_backtrace()
This function shows the history of function calls that led to an error.
π Example: Debugging Function Calls
<?php function test() { debug_print_backtrace(); } test(); ?>
Output: A trace of function calls.
πΉ 5. Using die()
and exit()
for Quick Debugging
Sometimes, stopping execution at a certain point can help locate an issue.
π Example: Using die()
<?php echo "Before error <br>"; die("Something went wrong!"); echo "This will never be printed."; ?>
Result: The script stops at die()
.
πΉ 6. Writing Logs with error_log()
Use error_log()
to save error messages in a log file instead of displaying them.
π Example: Writing to an Error Log
<?php error_log("This is a custom error!", 3, "errors.log"); ?>
Tip: Check the errors.log
file for logged errors.
π― Key Takeaways
error_reporting(E_ALL)
β Show all errors.var_dump()
β Check variable types and values.print_r()
β Print arrays in a readable format.debug_backtrace()
β Trace function calls.die()
β Stop script execution for debugging.error_log()
β Log errors instead of displaying them.
π Practice Time!
Try debugging a function with multiple parameters. Can you print out each variable’s value before the function runs? π€