How do I get PHP errors to display?

To display PHP errors, you can configure PHP settings via php.ini, .htaccess, or directly in your PHP script. Here are the most common methods:

1. Configure php.ini (Recommended for Development)

Edit your php.ini file (location varies by OS/server) and set:

display_errors = On       ; Show errors on screen
display_startup_errors = On ; Show errors during PHP startup
error_reporting = E_ALL   ; Report all errors, warnings, and notices

Restart your web server (e.g., Apache, Nginx) after making changes.

2. Override Settings in Your PHP Script

Add these lines at the top of your PHP file:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

This works if your server allows runtime configuration (not all hosts permit this).

3. Use .htaccess (Apache Servers)

Add these lines to your .htaccess file:

php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting E_ALL

4. Check Syntax Errors

If your script has a syntax error (e.g., missing semicolon), PHP won’t execute ini_set(). For syntax debugging:

php -l your_script.php  # Lint the file for syntax errors

5. Enable Error Logging

If you can’t display errors, log them to a file:

; In php.ini
log_errors = On
error_log = /path/to/php_errors.log

Check the log for details:

tail -f /path/to/php_errors.log

Common Error Levels

  • E_ALL: All errors and warnings.
  • E_ERROR: Fatal runtime errors.
  • E_WARNING: Non-fatal warnings.
  • E_NOTICE: Code suggestions (e.g., undefined variables).
  • E_STRICT: Coding standards (included in E_ALL in PHP 7+).

Example for Development

<?php
// Enable full error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Trigger a notice (e.g., undefined variable)
echo $undefinedVariable;

This will display:

Notice: Undefined variable: undefinedVariable in /path/to/file.php on line 6

Important Notes

  • Never enable display_errors in production – it exposes sensitive info.
  • Use try/catch blocks for exceptions and handle errors gracefully.
  • For production, log errors (log_errors = On) instead of displaying them.

By following these steps, you’ll see PHP errors directly in your browser or logs for debugging.

Leave a Reply

Your email address will not be published. Required fields are marked *