Error handling and logging in PHP applications
An error has two audiences: the person at the screen, who wants to know what to do next, and the team, who need to know what happened. This article shows how a PHP application serves both without telling one too much and the other too little.
What you will learn
The short answer
Keep the two audiences strictly apart. The user receives a short, understandable message and a reference code. The team receives everything needed to find the cause in the log, under the same code: error class, message, file, line and context. In technical terms: in production, log errors rather than displaying them; turn warnings into exceptions; catch exceptions only where you can do something useful with them; install a global handler for everything else; log with a level and context, and keep secrets out.
Errors, exceptions and warnings
Since PHP 7, most serious problems are reported by throwing an Error, for example a TypeError when an argument has the wrong type. Your own exceptions and those of libraries, on the other hand, are Exceptions. Both implement the Throwable interface but form separate branches: Error does not extend Exception. Your own classes cannot implement Throwable directly; they extend Exception or one of its subclasses.
| Branch | Examples | Meaning |
|---|---|---|
Error | TypeError, ValueError, DivisionByZeroError, UnhandledMatchError | programming mistakes; according to the manual they generally require a fix to the code rather than handling at runtime |
Exception | RuntimeException, PDOException, ErrorException, your own classes | exceptional situations the code can react to |
| Warning, notice | E_WARNING, E_NOTICE, E_DEPRECATED | reported but not thrown; the script carries on |
The third row is the treacherous one. file_get_contents() on a missing file emits a warning and returns false; if nobody checks, the code carries on calculating with false. A custom error handler turns such messages into an ErrorException:
<?php
declare(strict_types=1);
function netPrice(int $grossCents): int
{
return intdiv($grossCents * 100, 119);
}
// catch (Exception) does not see engine errors: TypeError is an Error
try {
try {
netPrice('11900'); // string passed under strict_types
} catch (Exception $e) {
echo "never reached\n";
}
} catch (Throwable $t) {
echo get_class($t), ' is Exception? ', var_export($t instanceof Exception, true), "\n";
}
// Warnings are not thrown by default; an error handler turns them into exceptions
set_error_handler(function (int $level, string $message, string $file, int $line): bool {
if (!(error_reporting() & $level)) {
return false; // respect the configured error level
}
throw new ErrorException($message, 0, $level, $file, $line);
});
try {
$config = file_get_contents(__DIR__ . '/missing.ini');
} catch (ErrorException $e) {
echo 'caught: ', $e->getMessage(), "\n";
}TypeError is Exception? false — the inner catch (Exception) does not apply, only Throwable does. Then caught: file_get_contents(…): Failed to open stream: No such file or directory.The error_reporting() check inside the handler matters: the handler is called regardless of the configured error level and has to decide for itself. According to the manual, some error types, including E_ERROR and E_PARSE, never reach a custom handler at all. For those, PHP’s own log is all that remains, which is one more reason to keep log_errors switched on.
Where to catch and where to let it pass
Catching an exception is only worthwhile if you can do something at that point. Four cases justify it:
Anything that is none of these should travel on to the global handler. An empty catch block turns an error into a silent error, and silent errors cost more. For business cases, dedicated exception classes such as InvoiceNotFound pay off: they can be caught specifically and mapped to a suitable response, such as 404 or 422, while unknown technical errors end up as 500. How this looks in the flow of a form submission is described in PHP in the backend.
A last line of defence for everything else
set_exception_handler() registers a function for every exception nobody has caught. According to the manual, execution stops after that function has run, so it is the place for a log entry and a response, not for a restart. The following example shows both, together with a small log writer:
<?php
declare(strict_types=1);
final class LogWriter
{
private const SECRET_KEYS = ['password', 'token', 'iban', 'authorization'];
/** @param array<string, mixed> $context */
public function log(string $level, string $message, array $context = []): void
{
foreach ($context as $key => $value) {
if (in_array(strtolower((string) $key), self::SECRET_KEYS, true)) {
$context[$key] = '[redacted]';
} elseif ($value instanceof Throwable) {
$context[$key] = get_class($value) . ': ' . $value->getMessage()
. ' at ' . basename($value->getFile()) . ':' . $value->getLine();
}
}
// one JSON line per entry: line breaks in user input cannot fake entries,
// and invalid UTF-8 is replaced instead of silently emptying the entry
$entry = ['level' => $level, 'message' => $message] + $context;
fwrite(STDERR, json_encode($entry, JSON_INVALID_UTF8_SUBSTITUTE) . "\n");
}
}
final class InvoiceNotFound extends RuntimeException {}
$log = new LogWriter();
$requestId = bin2hex(random_bytes(4));
set_exception_handler(function (Throwable $e) use ($log, $requestId): void {
$log->log('error', 'Unhandled exception', ['request_id' => $requestId, 'exception' => $e]);
echo "Sorry, that did not work. Please quote reference $requestId.\n";
});
$log->log('info', 'Login attempt', ['user' => "anna\nlevel=critical", 'password' => 'hunter2']);
throw new InvoiceNotFound('Invoice R-2026-0815 not found');[redacted], the line break in the user name as \n inside the entry; then the error entry with class, message, file and line, and for the user only Sorry, that did not work. Please quote reference … with the same code.In a web application the handler also sets status code 500 and returns an error page rather than a line of text. The log writer is deliberately minimal. In real projects you would use a library implementing the PSR-3 interface; the principle is the same.
The settings that go with it
| Setting | Development | Production |
|---|---|---|
display_errors | On | Off — according to the manual, never on systems connected to the internet |
log_errors | On | On — the manual strongly advises logging instead of displaying |
error_log | any | a file the web server user can write to, or syslog |
error_reporting | E_ALL | E_ALL (default since PHP 8.0) |
What belongs in the log
PSR-3, the logger recommendation of the PHP-FIG, defines eight levels and describes each one in a sentence in the interface code, some with examples. The right-hand column summarises these descriptions and adds examples of our own.
| Level | When |
|---|---|
emergency, alert | The application is unusable, or someone has to step in immediately, for example because the database is unavailable. |
critical | A component of the application is unavailable, or an unexpected exception has occurred. |
error | An operation has failed and needs attention. |
warning | Unusual but handled: a retry, a fallback. |
notice, info | Notable events in normal operation: a login, an export created. |
debug | Detail for troubleshooting; usually switched off in production. |
A message needs context: an array with the details that make the case distinguishable, such as order number, user ID or reference code. PSR-3 provides placeholders such as {order} in the message, which are filled from the context, and specifies that an exception in the context goes under the key exception. Keep the message text constant and the variable parts in the context; then identical errors can be counted.
A reference code per request links the user’s message to the log. It also helps when an operation passes through several systems, for example via a queue: pass it along and you can find every related entry.
What has no place in the log
The OWASP logging cheat sheet lists data that should not go into a log as it is, but should be removed, masked or hashed first. Among them:
The log writer in the example therefore replaces known keys with [redacted]. That is a safety net, not a substitute for care: the safest data is the data that never reaches the context. Pay particular attention to exception messages from database drivers and HTTP clients, which can contain whole requests including headers.
A second risk is log injection: if an input contains a line break, it can look like a separate entry in a plain-text log. OWASP recommends structured formats such as JSON. In the example, the user name anna\nlevel=critical therefore ends up as one value within a single line. The JSON_INVALID_UTF8_SUBSTITUTE option replaces invalid UTF-8 characters; without it, json_encode() returns false for such input and the entry would be empty.
A hypothetical example
The message “An error has occurred”
A member of staff reports that a new customer cannot be created. All she sees is a generic notice. Because there is a reference code underneath, the team finds the entry within seconds: a PDOException with SQLSTATE 23000, a violated uniqueness rule. The customer number already exists.
Technically the application was right; from a business point of view it failed, because a foreseeable case ended as a technical error. The fix was small: a check for an existing number and a message next to the field. The lesson applies generally: recurring entries at level error that are really user mistakes belong in input validation. A log that someone reads regularly reveals them.
Common misconceptions
Further sources
- PHP: Error - Manual base class of internal errors
- PHP: Throwable - Manual common interface of Error and Exception
- PHP: set_exception_handler - Manual global handler, end of execution
- PHP: set_error_handler - Manual custom error handler, error types it cannot handle
- PHP: Runtime Configuration - Manual display_errors, log_errors, error_log
- PSR-3: Logger Interface log levels, placeholders, context
- Logging - OWASP Cheat Sheet Series what to keep out of logs, log injection
About the author
Fabian Lücker is managing partner of PHP Schmiede KG in Rheine and has worked in software development since 2007. He is responsible for development and design, and writes here about decisions that come up in real projects.