PHP Debugging Techniques

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;
?>

Try It Now

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);
?>

Try It Now

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);
?>

Try It Now

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();
?>

Try It Now

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.";
?>

Try It Now

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");
?>

Try It Now

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? πŸ€”