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? ๐ค