How to Enable Error Display in PHP

1. Quick Way to Enable Errors

When working on a project, it's crucial to see errors for prompt debugging. Use the following code to enable error reporting. This approach is perfect for development but keep in mind: leaving error display enabled on a production server is not safe.

This code enables:

  • Displaying all errors, warnings, and notices;
  • Showing errors that occur during PHP's startup phase.
PHP
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Note: This method does not display syntax errors (e.g., a missing semicolon). To address such issues, you need to work with php.ini settings or .htaccess.

2. Enabling Errors via php.ini

If errors are still not visible after using ini_set, check your php.ini file. This is the main configuration file for PHP. Add the following lines to it:

PHP.INI
display_errors = on
error_reporting = E_ALL

To locate your php.ini file, use the phpinfo() function in a PHP script. Look for the Loaded Configuration File entry in the output.

Tip: Restart your server after making changes to apply the new settings.

3. Enabling Errors via .htaccess

Sometimes hosting providers don't allow access to php.ini but allow changes via the .htaccess file. Add the following lines:

.HTACCESS
php_flag display_errors on
php_flag display_startup_errors on

The .htaccess file should be in the root directory of your site or project folder. Note that not all servers support these directives.

Note: If errors are still not displayed, the server configuration might not allow modifying php.ini via .htaccess. Contact your server administrator for assistance.

4. Configuring Error Reporting

The error_reporting function allows developers to choose which types of errors will be displayed. For example:

  • E_ERROR — critical errors that halt script execution;
  • E_WARNING — warnings that do not stop script execution;
  • E_NOTICE — notices, such as using undefined variables;
  • E_ALL — all possible error and warning types.

Example of setting up to display only warnings:

PHP
error_reporting(E_WARNING);

To hide notices while showing other errors:

PHP
error_reporting(E_ALL & ~E_NOTICE);

The & ~ symbol allows excluding specific error types from display.

5. Logging Errors to a File

On production servers, it's recommended to log errors instead of displaying them to users. Use the error_log function for this purpose. It accepts up to four parameters:

  1. Error message;
  2. Logging type (0 — standard log, 1 — send to email, 3 — write to a file);
  3. Log file path (for type 3);
  4. Optional additional headers.

Example of writing an error to a file:

PHP
error_log("Error: file not found", 3, "logs/errors.log");

Ensure that the path to the logs/errors.log file is writable.

To send errors via email:

PHP
error_log("Critical error!", 1, "admin@example.com");

Important: For this function to work, configure SMTP parameters in php.ini.

6. Disabling Errors

Sometimes it's necessary to completely disable error display (e.g., to prevent sensitive data leaks in a production environment). Use the following code:

PHP
error_reporting(0);
ini_set('display_errors', 0);

Note: You can keep error logging enabled for analysis even if they are not displayed in the browser.

7. Checking PHP Configuration

Sometimes it’s important to check the current PHP settings, including the path to the loaded php.ini file. Use the phpinfo() function for this purpose. It outputs detailed information about the current PHP configuration, including:

  • The loaded configuration file (Loaded Configuration File);
  • Installed modules and their versions;
  • Available directives and their values.

Example:

PHP
phpinfo();

Tip: Never leave this file accessible on your server, as it contains a lot of sensitive information about your environment.

8. Displaying Only Critical Errors

Sometimes it’s necessary to display only fatal errors, avoiding less significant warnings or notices. Use the following code:

PHP
error_reporting(E_ERROR);

You can also combine parameters, for example:

PHP
error_reporting(E_ERROR | E_PARSE);

This configuration will display only critical errors and syntax errors.

9. Configuring Error Logs on the Server

At the server level, you can specify the path to the error log file. For Apache, use the following directive:

APACHE
ErrorLog "/var/log/apache2/errors.log"

For Nginx, the equivalent directive is:

NGINX
error_log /var/log/nginx/errors.log;

Ensure the log file is writable. These settings are especially useful for server-level debugging.

10. Email Notifications for Critical Errors

If you want to receive email notifications for critical errors, use the error_log function with parameter 1. Example:

PHP
error_log("Critical error!", 1, "admin@example.com");

Before using this, ensure that SMTP parameters are configured in php.ini:

  • SMTP — address of the SMTP server;
  • smtp_port — SMTP port;
  • sendmail_from — sender’s email address.

Note: This function is suitable only for critical messages and can be used alongside file logging.

11. Handling Errors with Exceptions

PHP supports exception handling, which allows you to catch and handle errors in try/catch blocks. This is useful for managing errors at the application logic level.

Simple example of using exceptions:

PHP
try {
    // Code that may throw an exception
    if (!file_exists("example.txt")) {
        throw new Exception("File not found");
    }
    echo "File found!";
} catch (Exception $e) {
    // Handle the error
    echo "Error: " . $e->getMessage();
}

Here, the throw method triggers an exception, and the catch block catches and handles it.

Tip: Use exceptions to handle errors in your application logic rather than for standard errors, which are better handled via error_reporting.

12. Creating Custom Exceptions

You can create custom exception classes to better structure error handling in complex projects. Here’s an example:

PHP
class MyCustomException extends Exception {
    public function customMessage() {
        return "Error on line {$this->getLine()} in file {$this->getFile()}: {$this->getMessage()}";
    }
}

try {
    // Code that triggers an exception
    throw new MyCustomException("An error occurred");
} catch (MyCustomException $e) {
    // Handle the custom exception
    echo $e->customMessage();
}

This approach simplifies debugging and makes error handling more structured.

Note: Custom exceptions are useful for creating specific error types, such as database, network, or authentication errors.

13. Catching Fatal Errors

Fatal errors usually terminate script execution. However, you can catch them using the register_shutdown_function function. Example:

PHP
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && ($error["type"] === E_ERROR || $error["type"] === E_PARSE)) {
        echo "Fatal error: {$error['message']}";
    }
});

This function registers a callback that executes when the script ends, allowing you to process the last error.

Note: Ensure your script continues to log critical errors to a file or database.

14. Using a Custom Error Handler

You can override PHP’s default error-handling behavior using the set_error_handler function. Example:

PHP
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "Error [{$errno}] in file {$errfile} on line {$errline}: {$errstr}";
    // You can log or process the error
    return true; // Prevents execution of the default handler
}

set_error_handler("customErrorHandler");

// Example error
echo $undefined_variable;

This code allows you to customize error handling to suit your application’s needs.

Tip: Use set_error_handler to create a flexible error-handling system for your projects.