Error handling is a crucial part of PHP development that often separates beginner code from professional-grade applications. When done correctly, error handling prevents application crashes, improves debugging, enhances user experience, and keeps sensitive system details hidden from the end user.
In this guide, we’ll explore proven best practices to handle errors in PHP effectively—whether you're building a small script or a production-ready enterprise solution.
1. Use the Right Error Reporting Settings
Your error reporting strategy should change depending on the environment:
Development
Display all errors so you can catch bugs early.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Production
Never show raw errors to users. Log them instead.
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/var/log/php_errors.log');
Always separate environment configs using .env
or a config file.
2. Catch Exceptions Using try...catch
Use try-catch
blocks to safely handle code that may throw exceptions.
try {
$content = file_get_contents("data.json");
} catch (Exception $e) {
error_log("Error: " . $e->getMessage());
echo "Oops! Something went wrong.";
}
You can even extend Exception
to define your own error types.
3. Create Custom Error Handlers
PHP allows you to intercept runtime warnings and notices:
function handleErrors($errno, $errstr, $errfile, $errline) {
error_log("PHP Error [$errno]: $errstr in $errfile on line $errline");
}
set_error_handler("handleErrors");
This way, your app continues running while errors are logged quietly.
4. Detect Fatal Errors Gracefully
For fatal or shutdown errors, use:
register_shutdown_function(function () {
$error = error_get_last();
if ($error && $error['type'] === E_ERROR) {
error_log("Fatal Error: {$error['message']} in {$error['file']} on line {$error['line']}");
}
});
This catches issues like memory limits, syntax failures, and critical crashes.
5. Use Logging Tools & Framework Features
If you’re using Laravel, Symfony, or other modern frameworks, use their built-in logging systems (like Monolog).
Example in Laravel:
Log::error('Payment failed', ['user_id' => auth()->id()]);
You can also integrate tools like:
- Sentry
- Bugsnag
- Laravel Telescope
- Slack alerts via webhook
6. Show Clean Error Messages to Users
Users shouldn’t see technical messages like “Fatal error: Call to undefined function”. Instead, show a generic message and log the rest.
echo "Something went wrong. Please try again later.";
Create custom 404, 500, and fallback error pages to enhance UX.
7. Monitor & Review Logs Regularly
Logging is useless if you don’t review it. Set up scheduled checks or alerts for high-severity issues.
Log errors with context (like user ID, route, request payload) for faster debugging.
8. Summary Table
Best Practice | Why It Matters |
Set correct error_reporting | Controls visibility and logging |
Use try...catch | Prevents app crashes on exceptions |
Use custom error handlers | Manages runtime warnings elegantly |
Handle fatal errors | Avoids total crashes, logs them safely |
Avoid showing raw errors | Protects app integrity and user trust |
Log with context | Makes debugging easier and faster |
Use error monitoring tools | Get real-time alerts and insights |