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.