StreetGeek Academy · PHP Foundations

🧩 Module 11: Error Handling and Debugging

Objective: Learn how to identify, handle, and debug PHP errors using built-in error types,
exception handling, and logging techniques to maintain reliable, production-ready applications.

🔹 1. Why Error Handling Matters

Errors are inevitable — every developer faces them. Good developers plan for them, detect them early, and make sure
users never see raw error messages like:

Fatal error: Uncaught Exception in /var/www/html/index.php on line 7

You’ll learn to:

  • Detect issues early (debug mode)
  • Handle them gracefully (try/catch)
  • Log them securely (error logs)
  • Prevent them before deployment

🔹 2. PHP Error Types

Type Description Example
Notice Minor issue (undefined variable) $x used before assignment
Warning Non-fatal error Including missing file
Parse Error Syntax issue Missing semicolon
Fatal Error Critical — stops execution Calling undefined function

🧠 Only fatal errors stop the entire script immediately.

🔹 3. Displaying and Hiding Errors

During development, you want to see errors. In production, you hide them and log them instead.

Show errors (development)

ini_set('display_errors', 1);
error_reporting(E_ALL);

Hide errors (production)

ini_set('display_errors', 0);
error_reporting(0);

✅ Always log errors even when they are hidden from users.

🔹 4. Error Logging

You can direct errors to a log file:

ini_set('log_errors', 1);
ini_set('error_log', 'errors.log');

Example custom log entry:

error_log("User failed login attempt at " . date("Y-m-d H:i:s"));

🧠 The log file is invaluable for debugging user issues after deployment.

🔹 5. Basic Error Example

<?php
// Undefined variable Notice
echo $user;

// Missing semicolon Parse Error
echo "Hello"
?>

✅ You’ll see different levels of errors depending on your error_reporting settings.

🔹 6. Try, Catch, and Finally (Exception Handling)

PHP uses exceptions to handle serious errors gracefully — instead of crashing your program.

<?php
try {
    if (!file_exists("data.txt")) {
        throw new Exception("File not found!");
    }
    $content = file_get_contents("data.txt");
    echo $content;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    echo "<br>Process completed.";
}
?>

✅ Output:

Error: File not found!
Process completed.

🧠 finally always runs, even if an exception occurs.

🔹 7. Custom Exceptions

You can define your own error rules and responses.

<?php
class CustomException extends Exception {}

function divide($a, $b) {
    if ($b == 0) {
        throw new CustomException("Cannot divide by zero!");
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (CustomException $e) {
    echo "Caught Exception: " . $e->getMessage();
}
?>

✅ Output:

Caught Exception: Cannot divide by zero!

🔹 8. Handling Multiple Exceptions

<?php
try {
    throw new Exception("General error!");
} catch (InvalidArgumentException $e) {
    echo "Invalid argument!";
} catch (Exception $e) {
    echo "Caught general exception: " . $e->getMessage();
}
?>

🧠 PHP checks catch blocks in order — the first match runs.

🔹 9. Debugging Tools

  • var_dump() – Shows detailed info about a variable:

    var_dump($_POST);
  • print_r() – Displays array or object in readable form:

    print_r($_SESSION);
  • die() / exit() – Stops script execution immediately:

    if (!$conn) die("Database connection failed!");
  • debug_backtrace() – Shows the stack of function calls leading to an error.

🔹 10. Using Xdebug (Advanced)

If you’re using LocalWP, XAMPP, or VS Code, install Xdebug to:

  • Set breakpoints
  • Step through code
  • Inspect variables in real time

🧩 Recommended for serious debugging — covered deeper in the StreetGeek Advanced PHP Track.

🧩 Hands-On Practice

Exercise 1: Display and Log

Create error-demo.php:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

function testError() {
    echo $undefinedVar; // Notice
    include("missing.php"); // Warning
}
testError();
?>

✅ See multiple errors reported.

Exercise 2: Try / Catch

Create trycatch-demo.php:

<?php
try {
    $result = 10 / 0;
} catch (DivisionByZeroError $e) {
    echo "Error: Cannot divide by zero!";
}
?>

✅ Gracefully handles a fatal error.

Exercise 3: Logging to File

Create log-demo.php:

<?php
ini_set('log_errors', 1);
ini_set('error_log', 'app-errors.log');

error_log("Custom log entry from " . date("Y-m-d H:i:s"));
echo "Error logged successfully!";
?>

✅ Check your directory for app-errors.log.

Exercise 4: Custom Exception

Create custom-exception.php:

<?php
class LoginException extends Exception {}

function login($user, $pass) {
    if ($user != "admin" || $pass != "1234") {
        throw new LoginException("Invalid login credentials!");
    }
    return "Welcome, $user!";
}

try {
    echo login("guest", "wrongpass");
} catch (LoginException $e) {
    echo "Error: " . $e->getMessage();
}
?>

✅ Prints an error message without crashing the app.

🎯 Mini Project – Safe File Reader with Error Handling

Goal: Create a file reader that checks for file existence, handles exceptions,
and logs errors safely.

Steps:

  • Create safe-reader.php
  • Use this code:
<?php
ini_set('log_errors', 1);
ini_set('error_log', 'reader-errors.log');

function readFileSafe($file) {
    if (!file_exists($file)) {
        throw new Exception("File not found: $file");
    }
    return file_get_contents($file);
}

try {
    echo readFileSafe("notes.txt");
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
    error_log("[" . date("Y-m-d H:i:s") . "] " . $e->getMessage());
}
?>

✅ If the file doesn’t exist, it displays a clean error message and logs it.

🧾 Module 11 Quiz

# Question Options Correct
1 What function sets PHP error reporting? a) error_setup() · b) error_reporting() · c) ini_set() b
2 What happens if a Fatal Error occurs? a) Script continues · b) Script stops · c) Error ignored b
3 Which block always runs in a try/catch? a) finally · b) after · c) run a
4 What function is used to log custom messages? a) debug() · b) error_log() · c) log_message() b
5 What keyword throws a custom error? a) raise · b) throw · c) catch b

💪 Challenge Task – Login Error Tracker

Objective: Combine login validation, try/catch, and error logging to create
a secure login system that tracks failed attempts.

Create login-track.php and add:

<?php
ini_set('log_errors', 1);
ini_set('error_log', 'login-errors.log');

try {
    $user = $_POST['user'] ?? "";
    $pass = $_POST['pass'] ?? "";

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if ($user !== "admin" || $pass !== "1234") {
            throw new Exception("Failed login attempt by: $user");
        }
        echo "<p>Welcome, $user!</p>";
    }
} catch (Exception $e) {
    echo "<p style='color:red;'>Error: Invalid login.</p>";
    error_log("[" . date("Y-m-d H:i:s") . "] " . $e->getMessage());
}
?>
<form method="POST" action="">
  Username: <input type="text" name="user"><br>
  Password: <input type="password" name="pass"><br>
  <input type="submit" value="Login">
</form>

✅ Every failed login is logged safely in login-errors.log.

🧾 Submission Checklist

  • error-demo.php → shows different error types
  • trycatch-demo.php → uses exception handling
  • log-demo.php → logs errors correctly
  • safe-reader.php → handles file safely
  • ✅ Challenge task completed
  • ✅ Quiz done

🏁 Next Step: In Module 12, you’ll put everything together in your Final Project:
Simple Blog System — combining functions, forms, file I/O, sessions, and MySQL into a working dynamic PHP website.
You’ll create posts, edit them, delete them, and secure your admin area — just like a lightweight CMS.