π§© 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.