Overview
Errors are inevitable; leaking them to visitors is not. A production application should record enough detail for diagnosis while returning a safe, consistent response to the user.
Separate development and production behavior
During development, enable useful error reporting and display errors locally. In production, set display_errors=Off and log_errors=On, and send logs to a protected destination. Configure these values in the correct PHP SAPI configuration because CLI, PHP-FPM and Apache modules may load different ini files.
Use a centralized exception boundary
Register an exception handler at bootstrap. It should log the exception with a correlation identifier, then return a generic error page or JSON response. Do not expose SQL, filesystem paths, credentials, stack traces or raw exception messages to visitors.
Catch only what you can handle
Catch a specific exception when the application can recover or translate it meaningfully. Avoid broad catch (Throwable) blocks that silently hide programming errors. If you catch a broad throwable at the top-level boundary, log it and terminate the request safely.
Logging practices
Include timestamp, severity, request identifier and relevant non-sensitive context. Do not log passwords, access tokens, session cookies or full payment details. Rotate logs and restrict filesystem permissions. For distributed applications, use structured logs and a central collector.
Official references
PHP error handling PHP exceptions
Configure production behavior
Production should log errors without displaying them to visitors. Configure this in the PHP runtime and application bootstrap, not only in a page template. Ensure the log directory is outside the public document root and writable only by the application account.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
Register a central exception handler that logs the exception and returns a generic error page or JSON response. Do not expose exception messages, SQL statements or stack traces to the browser.
Catch exceptions at the right boundary
Catch an exception when the application can take a meaningful action: retry a transient operation, roll back a transaction, show a validation message or translate an infrastructure failure into an HTTP response. Avoid empty catch blocks that hide failures.
Separate operational and user errors
Invalid form data is expected and should be returned as a field-level response. A database outage is an operational failure and should be logged with context and surfaced as a safe 503 or 500 response. Avoid logging passwords, session IDs, access tokens or full payment details.
Verify logging in deployment
Test that the application can write logs, that log rotation is configured and that permissions do not allow public downloads. Monitor disk usage: a failing application can fill a filesystem if it logs the same exception on every request.