Error.php in PHP: What It Is and How to Use It
Error.php is a common, non-core PHP file used to display or route error messages. This guide explains what it is, where it might appear, and how to implement safe error handling.
error.php is not a PHP core feature. It's a conventional filename chosen by developers for a script that handles errors in a PHP project. Its exact role depends on how a site is configured.
What is error.php?
Not a PHP core feature
Error handling in PHP is configured with directives in php.ini or in the code. A file named error.php is simply a chosen convention for a page that displays an error message or routes error details to a log.
Common roles
The error.php file may serve as:
- A user-friendly error page shown to visitors when something goes wrong
- A central point to log error details and optionally display debugging information in development
- A fallback when a request cannot be fulfilled
Where you might see error.php
Error.php is common in older or custom applications, or in setups where a front controller routes all errors to a single page. Some servers or frameworks may be configured to point 500-level errors to /error.php so visitors see a friendly message instead of a raw error.
Centralized error handling
A central error handler funnels errors from various parts of the app into a single place. In PHP this can be done with seterrorhandler and setexceptionhandler, or by a framework's error handling mechanism, which may route to error.php. The goal is to log details securely while presenting a clean message to users.
Best practices for error pages
- Hide sensitive details from end users and avoid leaking stack traces.
- Use appropriate HTTP status codes (500 for server errors, 404 for not found).
- Log full error information on the server and keep logs secure.
- Keep a consistent look and feel with your site branding.
- Consider a development mode that shows more details locally, but not on production.
A simple error.php example
Here is a minimal production-friendly error.php snippet that sets a 500 status and shows a generic message:
<?php
// error.php - a simple, production-friendly error page
http_response_code(500);
if (php_sapi_name() != 'cli') {
// Ensure consistent layout if not running in CLI
include __DIR__ . '/header.php';
echo '<h1>Something went wrong</h1>';
echo '<p>Please try again later.</p>';
include __DIR__ . '/footer.php';
}
?>
Share This Article
Spread the word on social media
Anne Kanana
Comments
No comments yet. Be the first to share your thoughts!