Imagine you're building a website, and suddenlyโBOOM! ๐ฅ Your page breaks with a cryptic error message. Ever been there? ๐ Thatโs why error handling is crucial in PHP!
A well-handled error can:
โ
Prevent your site from crashing
โ
Improve user experience
โ
Help debug problems easily
In this step-by-step guide, youโll learn how to catch errors and exceptions like a pro, with real-world examples and a mini-project at the end! ๐
๐ฏ Understanding PHP Errors
PHP has four main types of errors:
Error Type | Description | Example |
---|---|---|
Fatal Error | Stops script execution completely | Calling an undefined function |
Parse Error | Syntax mistake in the code | Missing ; in PHP |
Warning | Non-fatal, script continues | Using a missing file |
Notice | Minor issue, script continues | Using an undefined variable |
๐ฅ How to see errors?
Enable error reporting with:
error_reporting(E_ALL);
ini_set('display_errors', 1);
This displays all PHP errors while developing.
1๏ธโฃ Handling Errors with try...catch
Basic Error Handling
<?php
try {
echo 10 / 0; // Division by zero (error!)
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
๐ What happens?
try
runs the code that might fail.catch
handles the error gracefully.- The script wonโt crash unexpectedly.
2๏ธโฃ Using set_error_handler()
for Custom Error Messages
Custom Error Handler
<?php
function customError($errno, $errstr) {
echo "Error [$errno]: $errstr <br>";
}
set_error_handler("customError");
// Trigger an error
echo 10 / 0;
?>
๐ฅ Why use this?
set_error_handler()
lets you define how errors are handled globally.- Prevents ugly PHP error messages.
3๏ธโฃ Using error_log()
to Store Errors
Logging Errors to a File
<?php
function logError($errno, $errstr) {
error_log("Error [$errno]: $errstr", 3, "errors.log");
}
set_error_handler("logError");
// Simulate an error
echo 10 / 0;
?>
๐ฅ Why use this?
- Stores errors in errors.log instead of showing them to users.
- Useful for debugging in production.
4๏ธโฃ Handling Exceptions in PHP
Exceptions are better than errors for handling unexpected issues.
Using throw
to Trigger an Exception
<?php
function divide($a, $b) {
if ($b == 0) {
throw new Exception("Cannot divide by zero!");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
echo "Caught Exception: " . $e->getMessage();
}
?>
๐ What happens?
throw new Exception()
manually triggers an exception.- The
catch
block prevents crashes.
5๏ธโฃ Using finally
to Clean Up
Example: Closing a Database Connection
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=zeroexp_dev", "root", "");
echo "Connected successfully!";
} catch (Exception $e) {
echo "Database Error: " . $e->getMessage();
} finally {
echo "<br>Cleaning up resources.";
}
?>
๐ฅ Why use finally
?
- Runs whether or not an exception occurs.
- Great for closing connections, releasing memory, or logging actions.
๐ฏ Mini Project: User Login with Error Handling
Letโs build a real-world login system that handles:
โ
Missing username/password
โ
Database connection errors
โ
Wrong credentials
login.html
<form action="login.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
login.php
<?php
session_start();
try {
$conn = new PDO("mysql:host=localhost;dbname=zeroexp_dev", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = trim($_POST["username"] ?? '');
$password = trim($_POST["password"] ?? '');
if (empty($username) || empty($password)) {
throw new Exception("Both fields are required!");
}
// Fake authentication (replace with database check)
if ($username === "zerodev" && $password === "secret123") {
$_SESSION["username"] = $username;
header("Location: dashboard.php");
} else {
throw new Exception("Invalid credentials!");
}
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
dashboard.php
<?php
session_start();
if (!isset($_SESSION["username"])) {
echo "Access denied! <a href='login.html'>Login here</a>";
exit;
}
echo "Welcome, " . $_SESSION["username"] . "! <a href='logout.php'>Logout</a>";
?>
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: login.html");
?>
โ Whatโs Happening?
login.php
checks for errors (empty fields, wrong credentials).- If login is successful, the user is redirected to
dashboard.php
. - If not, an error message is displayed.
logout.php
clears the session and logs out the user.
๐ฅ Boom! You now have a secure PHP login system with error handling! ๐
๐ Final Thoughts
Now you know how to handle errors like a pro!
โ
Use try...catch
to prevent crashes
โ
Use set_error_handler()
for custom error handling
โ
Use error_log()
to track issues in production
โ
Use exceptions for better error control
๐ Next: Introduction to MySQL with PHP
Happy coding! ๐๐