Lesson 11 of 14 · 15m
Errors, Exceptions, and Logs Worth Reading at 3 A.M.
Throwable boundaries, argument values in traces, log-line injection, and JSON logs that survive parsers.
Since PHP 7, every failure is a Throwable. Error covers the engine — TypeError, ValueError, ArithmeticError, fatal conditions. Exception covers your domain — things your code throws deliberately. catch (Exception) at a boundary misses TypeError; the uncaught Throwable renders a fatal plus a stack trace, and where that trace goes is decided by ini, not by your code. Most of what's wrong with PHP error handling is people treating a rendering decision as a code decision.
The trace is a data leak
display_errors=On prints traces to the response — file paths, class names, and argument values unless zend.exception_ignore_args=1 (PHP 7.4+, and off by default). A failed PDO connect trace can carry the DSN and credentials inline. PHP ships two ini files — php.ini-development and php.ini-production — precisely because this default burned the ecosystem for years. Production gets display_errors=Off, log_errors=On, and a handler that renders a generic 500.
Debug pages are the same leak with better CSS. Laravel's Ignition error page was CVE-2021-3129 — a file-write plus phar-deserialization chain into RCE. The "helpful" debug surface was the vulnerability. Debug renderers belong behind authentication or off entirely; there is no third option that survives contact with the internet.
Handlers that do what you think
set_error_handler(function (int $severity, string $msg, string $file, int $line): bool {
if (!(error_reporting() & $severity)) { return true; } // @-suppressed / excluded
throw new ErrorException($msg, 0, $severity, $file, $line);
});
set_exception_handler(function (Throwable $e): void {
$log->error($e->getMessage(), ['exception' => get_class($e), 'trace' => $e->getTraceAsString()]);
http_response_code(500);
echo 'Internal error';
});Converting E_* to ErrorException is the standard idiom and it's why "notices are ignorable" stopped being true — an Undefined variable notice becomes a thrown exception you can trace to a line. The error_reporting() gate respects @-suppression and your configured level; skip it and @ turns into a landmine that still throws.
Some fatals bypass exception handlers entirely — engine E_ERROR paths die hard. register_shutdown_function plus error_get_last() is the last-chance log: run it, check for a fatal, write one clean log line before the process exits.
Logs are parsed output
A log line is data another program parses — which means \n in an attacker-controlled field is an injection. User alice\n[2026-11-16] INFO admin logged in forges a second line; CWE-117 names it "improper output neutralization for logs". It's not cosmetic: forged entries poison audits, and unescaped control bytes break JSON parsers mid-file. JSON-encode your log lines — Monolog's JsonFormatter exists for exactly this — or sanitize interpolations, but do one of them.
The other log bug is content: var_dump($_SERVER) in a log line writes your environment — including DB_PASS — to a file. Logging POST bodies writes passwords to disk. Redact known keys (password, token, authorization, anything env-shaped) before context reaches the handler; Monolog processors are the hook for attaching request_id and stripping fields in one place.
The practical shape
- Catch
Throwableat the request boundary, neverException. zend.exception_ignore_args=1in prod ini — argument values out of traces.- Monolog with
JsonFormatterto stdout — let the platform collect it; attachrequest_idvia a processor. register_shutdown_functionfor the fatals that skip handlers.logrotatefor anything writing to files —log_errorswithout rotation fills disks at 2 a.m.
Try this
Throw an exception inside a DB call carrying a credential-shaped argument, once with zend.exception_ignore_args=0 and once =1, and diff the trace. Then log a username containing \nroot login succeeded and look at the file. Both fixes take four minutes; the demonstrations are unforgettable.
Pitfalls
error_reporting=-1+ a converting handler makes every notice throwable — decide whether that's hygiene or noise for your codebase before enabling in anger.finallyruns before the exception propagates — cleanup belongs there, not duplicated intry/catch.- Never
catch (Throwable) {}silently — a swallowed error is a debugging tax someone pays later with interest.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
PHP 8.6 Finally Turns On the Session Settings You Were Told to Set in 2006
Every PHP hardening guide for two decades has told you to flip the same three session settings. PHP 8.6, due November 19, 2026, flips them for you: strict mode on, HttpOnly on, SameSite set to Lax.
Money Is Not a Float: Decimals, Rounding and Cents in PHP, Python and JavaScript
I ran the same money math through PHP 8.6, Python 3.15 and Node 26. They round 2.675 differently, bcadd('0.1', '0.2') returns 0, PHP's BcMath\Number turns a float 0.1 into 0 with only a deprecation notice, and JSON.parse quietly changes 9007199254740993 to ...992.
PHP OPcache, Preloading and the JIT, Measured on Laravel: One Setting Is 18x, One Costs You 19%, and the JIT Does Nothing
I ran Laravel 13 on PHP 8.6 FPM under six OPcache configurations and timed every one. OPcache itself was worth 18x, revalidate_freq=0 quietly cost 19%, preloading added 9%, and the JIT that doubles Zend's CPU benchmark moved a real page by 1%.
One Slow Call, Three Runtimes: How PHP-FPM, Python ASGI and Node Fall Over When a Dependency Takes 200 ms
I put the same 200 ms wait behind PHP-FPM, FastAPI on uvicorn and a plain Node server, then hit each one with 50 concurrent requests. Handled correctly, the async runtimes served 205-211 req/s against FPM's 19.6. One blocking call in the wrong place took both of them down to 4.98, slower than...