Error handling helps you identify, report, and manage problems that occur while a PHP program runs. PHP provides error reporting settings, custom error handlers, and exceptions to help developers build reliable applications.
Error handling is the process of detecting and managing problems in a program instead of allowing unexpected failures to go unnoticed.
Common PHP problems include:
Example:
<?php
$number1 = 10;
$number2 = 0;
if ($number2 !== 0) {
echo $number1 / $number2;
} else {
echo "Division by zero is not allowed.";
}
?>
This example checks the divisor before performing the calculation. Preventing predictable problems is often better than handling them after they occur.
PHP reports different kinds of problems depending on their severity and how the program is written.
<?php
echo $studentName;
?>
If the variable is undefined, PHP may report a warning or another diagnostic depending on the PHP version and context.
<?php
function greet() {
echo "Hello Student";
}
greet();
greet();
?>
Declaring the same named function twice in one execution causes a fatal error.
<?php
echo "Hello Student"
?>
The missing semicolon before the closing PHP tag can cause a parse error in this example.
Modern PHP also distinguishes between
Error and Exception objects.
Both implement the Throwable interface.
The error_reporting() function controls
which PHP errors are reported.
<?php
error_reporting(E_ALL);
$number = 100;
echo $number;
?>
E_ALL enables reporting for all standard
PHP error levels.
To enable full error reporting during development:
<?php
error_reporting(E_ALL);
ini_set("display_errors", "1");
ini_set("log_errors", "1");
?>
Put development settings before the code you are debugging. Server configuration may affect whether errors are displayed.
Important: On a production website, do not display detailed errors to visitors. Log errors privately and show users a general message instead.
The die() and exit() functions
terminate the current script. They are equivalent.
<?php
$file = "students.txt";
if (!file_exists($file)) {
die("The requested file does not exist.");
}
echo "File found successfully.";
?>
If the file does not exist, the script stops and displays the supplied message.
Using exit():
<?php
$age = 16;
if ($age < 18) {
exit("You are not eligible.");
}
echo "Access allowed.";
?>
Use these functions for simple termination when appropriate. In larger applications, exceptions and centralized error handling can provide better control.
The trigger_error() function raises a
user-generated PHP diagnostic.
<?php
$marks = 120;
if ($marks < 0 || $marks > 100) {
trigger_error(
"Marks must be between 0 and 100.",
E_USER_WARNING
);
}
echo "Marks: " . $marks;
?>
The second argument identifies the error level. Common user-generated levels include:
E_USER_NOTICEE_USER_WARNINGE_USER_ERRORA user-generated warning normally reports the problem but does not automatically stop the script. A user-generated error has different severity and can terminate execution.
For ordinary input validation, it is often clearer to return a validation message rather than generate a PHP diagnostic.
PHP provides set_error_handler() to
register a custom handler for supported error levels.
<?php
function myErrorHandler(
int $severity,
string $message,
string $file,
int $line
): bool {
error_log(
"PHP diagnostic: " . $message .
" in " . $file .
" on line " . $line
);
return true;
}
set_error_handler(
"myErrorHandler",
E_USER_WARNING | E_USER_NOTICE
);
trigger_error(
"This is a custom warning.",
E_USER_WARNING
);
restore_error_handler();
?>
The handler receives the error severity, message, filename, and line number.
Returning true indicates that the
handler has handled the diagnostic. Returning
false allows PHP's standard error
handler to continue processing it.
Custom error handlers do not handle every PHP error category. In particular, parse errors that prevent a file from being compiled cannot be handled by a handler registered inside that same file.
The error_log() function can write
diagnostic messages to the configured PHP error log.
<?php
try {
$file = "important.txt";
if (!file_exists($file)) {
throw new RuntimeException(
"Required file was not found."
);
}
echo "File is available.";
} catch (RuntimeException $e) {
error_log($e->getMessage());
echo "Sorry, the requested operation could not be completed.";
}
?>
In this example, the technical message is written to the server log while the visitor receives a general message.
Production best practices:
Database operations can fail because of connection
problems, invalid queries, or database constraints.
PDO exceptions can be handled with
try and catch.
<?php
require_once "db.php";
try {
$stmt = $pdo->prepare(
"SELECT id, name FROM students WHERE id = :id"
);
$stmt->execute([
"id" => 1
]);
$student = $stmt->fetch();
if ($student) {
echo htmlspecialchars(
$student["name"],
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
);
} else {
echo "Student not found.";
}
} catch (PDOException $e) {
error_log($e->getMessage());
echo "A database error occurred. Please try again later.";
}
?>
This example assumes the PDO connection in
db.php uses exception-based error handling.
PDO's default error mode is exception-based in PHP 8.0
and later, but setting it explicitly in your connection
configuration makes the intention clear.
<?php
$pdo->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
?>
Catch exceptions when you can respond appropriately. Avoid exposing raw database exception messages to visitors.
The following example validates user input, prevents division by zero, and handles unexpected exceptions.
<?php
$result = null;
$error = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$firstInput = $_POST["num1"] ?? "";
$secondInput = $_POST["num2"] ?? "";
if (
!is_scalar($firstInput) ||
!is_scalar($secondInput) ||
trim((string) $firstInput) === "" ||
trim((string) $secondInput) === "" ||
!is_numeric($firstInput) ||
!is_numeric($secondInput)
) {
$error = "Please enter two valid numbers.";
} else {
try {
$first = (float) $firstInput;
$second = (float) $secondInput;
if ($second == 0.0) {
throw new DivisionByZeroError(
"The divisor cannot be zero."
);
}
$result = $first / $second;
} catch (DivisionByZeroError $e) {
$error = $e->getMessage();
} catch (Throwable $e) {
error_log($e->getMessage());
$error = "An unexpected error occurred.";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Division Calculator</title>
</head>
<body>
<h2>Division Calculator</h2>
<form method="post">
<label for="num1">First Number:</label>
<input type="number" step="any" id="num1" name="num1" required>
<br><br>
<label for="num2">Second Number:</label>
<input type="number" step="any" id="num2" name="num2" required>
<br><br>
<button type="submit">Calculate</button>
</form>
<?php if ($error !== ""): ?>
<p style="color: red;">
<?= htmlspecialchars(
$error,
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
) ?>
</p>
<?php endif; ?>
<?php if ($result !== null): ?>
<p>
Result:
<?= htmlspecialchars(
(string) $result,
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
) ?>
</p>
<?php endif; ?>
</body>
</html>
This calculator demonstrates validation and exception handling together. In a real application, consider limits on input size and numeric range as well.
1. Which function controls which PHP errors are reported?
2. Which function can write a message to the PHP error log?
3. Which block handles a matching exception thrown inside a try block?