Skip to main content
PHP Backend Development Tutorial
CHAPTER 16 Beginner

Error Handling and Debugging in PHP

Updated: May 14, 2026
20 min read

# CHAPTER 16

Error Handling and Debugging in PHP

1. Introduction

Every programmer writes bugs. A senior developer isn't someone who never makes mistakes; they are someone who knows how to find and fix mistakes quickly. When your PHP application crashes and displays a terrifying "500 Internal Server Error" or a blank white screen, panic is not the solution. In this chapter, we will learn how to read PHP error logs, use try...catch blocks to handle fatal exceptions, and implement professional debugging workflows.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the difference between Notices, Warnings, and Fatal Errors.
  • Enable error reporting for local development.
  • Implement robust try...catch blocks for Exception handling.
  • Write custom error messages to secure server logs.

3. Beginner-Friendly Explanation

Imagine driving a car.
  • A Notice: The dashboard says you are low on windshield wiper fluid. The car still drives perfectly fine, but you should probably fix it.
  • A Warning: The "Check Engine" light turns on. The car is still moving, but something is wrong under the hood. It might break down soon.
  • A Fatal Error: The engine explodes. The car immediately stops.
In PHP, if you misspell a variable name, it's a Notice. If you forget to include a file, it's a Warning. If you forget a semicolon (;), the engine explodes (Fatal Parse Error) and the website instantly crashes. Debugging is the skill of reading the mechanic's report to figure out exactly which part exploded.

4. PHP Error Types

  1. 1. Notices: Minor, non-fatal issues (e.g., trying to echo an undefined variable). The script continues executing.
  1. 2. Warnings: More serious issues (e.g., include('missing_file.php')). The script continues executing, but part of the page might be broken.
  1. 3. Fatal Errors: Critical issues (e.g., calling a function that doesn't exist, or missing a semicolon). The script completely stops executing immediately.

5. Enabling Error Reporting

The dreaded "White Screen of Death" happens when PHP crashes but is configured to hide the error message. During local development, you want to see every single error. Put this at the very top of your index.php file:
php
12345678
<?php
// Display all errors on the screen (FOR DEVELOPMENT ONLY)
error_reporting(E_ALL);
ini_set(&#039;display_errors', 1);

// This will cause a Notice because $fake_variable doesn't exist
echo $fake_variable;
?>

6. Exception Handling (try...catch)

When connecting to external services (like a MySQL database or an API), things will inevitably fail. The database might be offline. If you don't handle this, the site throws a Fatal Error. We use Exceptions to catch the error before it crashes the site.
php
12345678910111213141516171819202122
<?php
function divideNumbers($numerator, $denominator) {
    if ($denominator == 0) {
        // We throw an exception instead of letting PHP crash
        throw new Exception("Division by zero is mathematically impossible.");
    }
    return $numerator / $denominator;
}

// The 'try' block runs the dangerous code
try {
    echo divideNumbers(10, 0);
    echo "This line will never execute because the error stops it.";
} 
// The 'catch' block safely catches the explosion and handles it
catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}

// Because we caught the error, the website CONTINUES running!
echo "<p>Welcome to the rest of the website!</p>";
?>

7. Logging Errors (The Production Workflow)

When you deploy your website to the internet, you MUST turn display_errors to 0. If a database fails, you do not want the hacker to see your database username printed on the screen. Instead of displaying errors, you Log them to a hidden text file on the server.
php
1234567891011
<?php
// Turn off screen display
ini_set(&#039;display_errors', 0);
// Turn on hidden logging
ini_set(&#039;log_errors', 1);
// Specify the hidden file
ini_set(&#039;error_log', '/var/log/php_errors.log');

// If this crashes, the user sees a blank page or a friendly "Oops" message,
// but the developer can open php_errors.log to see the exact stack trace.
?>

8. Basic Debugging Tools: var_dump()

When your logic isn't working, you need to look inside your variables to see what data they hold. var_dump() is a developer's best friend.
php
123456789
<?php
$user = ["name" => "Alice", "role" => "Admin"];

// Prints the exact structure, data type, and length of the variable to the screen
var_dump($user);

// To stop the script immediately after dumping (so HTML doesn't distract you)
die(); 
?>

9. Best Practices

  • Custom 404/500 Pages: Use your try...catch blocks to redirect users to a beautifully designed "Oops, something went wrong" page, rather than showing them a broken layout.

10. Common Mistakes

  • Leaving display_errors On in Production: This is a severe security vulnerability. Error traces reveal server file paths (C:\xampp\htdocs\...), database table names, and sometimes API keys. Always log errors in production; never display them.

11. Exercises

  1. 1. Explain the functional difference between a PHP Warning and a PHP Fatal Error regarding script execution.

12. Coding Challenges

  • Challenge: Write a try...catch block around a PDO database connection. If the connection fails, use the error_log() function to save the message "Database connection failed!" to the server log, and echo a friendly message to the user saying "Our servers are currently undergoing maintenance."

13. MCQs with Answers

Question 1

What causes the notorious "White Screen of Death" in a PHP application?

Question 2

What is the primary purpose of a try...catch block?

14. Interview Questions

  • Q: Differentiate between error handling in a local development environment versus a live production environment. What php.ini settings change?
  • Q: How do you debug an array or object to inspect its contents during runtime? What functions are available in PHP?

15. FAQs

Q: Are there better tools than var_dump() for debugging? A: Yes! Professional developers use a PHP extension called Xdebug. It integrates directly with IDEs like VS Code, allowing you to set "Breakpoints." The code will pause execution exactly at the breakpoint, and you can hover over variables to see their contents in real-time without writing var_dump().

16. Summary

In Chapter 16, we learned how to become mechanics. By understanding the severity of Notices, Warnings, and Fatal Errors, we can diagnose issues accurately. By implementing try...catch blocks, we can anticipate explosions (like database outages) and handle them gracefully without crashing the site. Most importantly, we learned the security distinction between displaying errors during local development and secretly logging them in production.

17. Next Chapter Recommendation

You have all the building blocks: Syntax, Forms, Databases, Sessions, Security, and Routing. Now, we put them all together. Proceed to Chapter 17: Building a Complete Backend Project.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·