# PHP Error Logging: The Complete Developer's Guide [2025]

By Dinesh Uprety
Published: 2025-04-07
Updated: 2025-04-08
Canonical: https://laranepal.com/blog/php-error-logging-the-complete-developers-guide-2025

# How to Log Errors in PHP: A Beginner’s Guide to Error Reporting and Debugging

[Handling errors](https://www.php.net/manual/en/function.set-error-handler.php) effectively is crucial for maintaining a
stable and secure PHP application. Instead of displaying raw
errors to users (which can expose sensitive information), you should log them for debugging while showing user-friendly
messages.

---

## Why Proper Error Handling Matters in PHP

Effective error logging is essential for:

- 🛡️ **Enhanced security** (hiding sensitive debug info from users)
- 🔍 **Easier debugging** (detailed error trails for developers)
- ⚡ **Improved stability** (graceful handling of runtime issues)

---

## 1. Configuring PHP Error Reporting

```php
<?php
    // Development environment settings
    error_reporting(E_ALL);             // Report all PHP errors
    ini_set('display_errors', 1);       // Show errors on screen
    ini_set('log_errors', 1);           // Enable error logging
    
    // Production environment settings
    /*
    error_reporting(E_ALL);
    ini_set('display_errors', 0);       // Never show errors to users!
    ini_set('log_errors', 1);
    */
?>
```

### Key Configuration Options:

Setting Purpose Development Production

| **Setting**                                                                                      | **Purpose**            | **Development**                                                                 | **Production**                                                                  |
|--------------------------------------------------------------------------------------------------|------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [`error_reporting()`](https://www.php.net/manual/en/function.error-reporting.php)                | Error level reporting  | [`E_ALL`](https://www.php.net/manual/en/errorfunc.constants.php#constant.e-all) | [`E_ALL`](https://www.php.net/manual/en/errorfunc.constants.php#constant.e-all) |
| [`display_errors`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors) | Show errors on screen	 | `1`  (On)                                                                       | `0` (Off)                                                                       |
| [`log_errors`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors)         | Enable error logging	  | `1` (On)                                                                        | `1` (On)                                                                        |

---

## 2. Creating a Custom Error Handler

```php
<?php
  function customErrorHandler($errno, $errstr, $errfile, $errline) {
      $logMessage = sprintf(
          "[%s] Error %s: %s in %s on line %d%s",
          date('Y-m-d H:i:s'),
          $errno,
          $errstr,
          $errfile,
          $errline,
          PHP_EOL // New line for readability
      );
      
      // Log to daily rotating file
      error_log($logMessage, 3, __DIR__.'/logs/errors_'.date('Y-m-d').'.log');
      
      // Optional: Send email for critical errors
      if (in_array($errno, [E_ERROR, E_USER_ERROR])) {
          error_log($logMessage, 1, 'info@laranepal.com');
      }
  }
  
  set_error_handler('customErrorHandler');
?>
```

### Handler Features:

* 📅 Daily log file rotation
* 📧 Critical error email alerts
* 🕒 Timestamped entries
* 📁 Secure file storage

---

## 3. Advanced Error Logging Techniques

### Log File Organization

```textmate
 /logs/
├── errors_2025-04-8.log
├── fatal_errors.log
└── archive/
    ├── errors_2024-11-01.log
    └── ...
```

### Security Best Practices

```apacheconf
# .htaccess protection for log files
<Files *.log>
  Order deny,allow
  Deny from all
</Files>
```

---

## 4. Handling Fatal Errors

Custom error handlers cannot catch fatal errors (e.g., syntax errors). For those, use:

* [`register_shutdown_function()`](https://www.php.net/manual/en/function.register-shutdown-function.php) to check for
  fatal errors.
* [`error_get_last`](https://www.php.net/manual/en/function.error-get-last.php) to retrieve the last error before
  shutdown.

```php
<?php
  register_shutdown_function(function() {
      $error = error_get_last();
      if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR])) {
          $message = sprintf(
              "[%s] FATAL ERROR (%s): %s in %s on line %d%s",
              date('Y-m-d H:i:s'),
              $error['type'],
              $error['message'],
              $error['file'],
              $error['line'],
              PHP_EOL
          );
          error_log($message, 3, __DIR__.'/logs/fatal_errors.log');
      }
  });
?>
```

### Fatal Errors Captured:

* [`E_ERROR`](https://www.php.net/manual/en/errorfunc.constants.php#constant.e-error) - Critical runtime errors
* [`E_PARSE`](https://www.php.net/manual/en/errorfunc.constants.php#constant.e-parse) - Syntax parsing errors
* [`E_CORE_ERROR`](https://www.php.net/manual/en/errorfunc.constants.php#constant.e-core-error) - PHP startup failures

---

## 5. Production-Ready Implementation Checklist

1. Configure `display_errors=0` in production
2. Implement custom error handler
3. Set up fatal error shutdown handler
4. Create secure log directory structure
5. Implement log rotation (daily/weekly)
6. Set proper file permissions (chmod 600)
7. Test error scenarios thoroughly

---

## Conclusion

Professional PHP error handling involves:

1. Proper error reporting configuration
2. Custom error handlers with logging
3. Secure log file management
4. Fatal error capture mechanisms
