PHP error reporting is crucial for debugging and troubleshooting PHP code. The developer can enable PHP error reporting by adjusting settings in the PHP configuration file (php.ini
) or via PHP code directly.
Display errors on the screen
Change display_errors
to On
to display errors on the screen.
display_errors = On
Set the level of errors
The directive error_reporting
determines which types of errors are reported. The value E_ALL
represents all error types, including warnings, notices, and errors. The setting error_reporting = E_ALL
is often recommended during the development and testing phases of the project.
error_reporting = E_ALL
A commonly recommended setting for production environments is error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING
. This configuration reports all errors except notices and warnings to users, which helps maintain security and performance while still capturing important errors for debugging purposes.
error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING
Runtime Configuration
You can also change these settings at runtime using PHP code. This method is useful if you don’t have access to the php.ini
file or if you want to change settings temporarily.
Example #1
<?
// Enable error reporting
ini_set('display_errors', 1);
// Your PHP code here
echo $undefinedVariable; // This will generate an error
// Disable error reporting
ini_set('display_errors', 0);
Example #2
<?
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Setting display_startup_errors
to 1
enables PHP to display startup errors. Startup errors occur during the PHP engine’s initialization process. It can help diagnose issues that occur during PHP initialization.