0 Day Analytics – PHP Error Module Developer Documentation

Table of Contents

1. Overview & Architecture

The PHP Error Tracker Module captures and persists PHP fatal errors, uncaught exceptions, warnings, deprecation notices, and other PHP error types into a dedicated database table. Unlike traditional error logging to debug.log, errors are stored in the database and survive log file rotations, WP_DEBUG toggles, and server restarts.

Key Capabilities

  • Automatic capture of PHP fatal errors via shutdown handler
  • Uncaught exception/error capture via custom exception handler
  • SHA-256 deduplication — repeated errors increment a counter instead of creating new rows
  • Automatic source identification (plugin, theme, WordPress core, or PHP)
  • PII and secret redaction before storage (Bearer tokens, JWTs, API keys, emails)
  • Configurable IP address privacy (raw, anonymized, or hashed storage)
  • Full-text search across all columns
  • Plugin-based filtering via dropdown
  • Sort by any column (ascending/descending)
  • CSV export with progress bar and cancellation support
  • View row details in a modal overlay via REST API
  • Stack trace display with source file links (ThickBox viewer)
  • Table truncate and drop via REST API with core table protection
  • Multisite-aware (captures blog_id)
  • Slack and Telegram notifications for fatal errors
  • Automatic record pruning via configurable retention period

Technology Stack

  • PHP 7.4+ (strict types)
  • WordPress WP_List_Table API (via Abstract_List)
  • WordPress REST API for row detail retrieval, truncate, and drop
  • wp-api-fetch for client-side REST calls
  • jQuery for modal, clipboard, and share interactions
  • ThickBox for source file viewing
  • Custom CSV export with batch processing via AJAX
  • PHP shutdown function and custom exception handler for error capture

2. File Map

advanced-analytics/
├── classes/
│   ├── vendor/
│   │   ├── lists/
│   │   │   ├── class-fatals-list.php             — WP_List_Table for PHP error data
│   │   │   └── views/
│   │   │       └── class-fatals-view.php          — Page rendering & action handlers
│   │   ├── entities/
│   │   │   └── class-wp-fatals-entity.php         — DB entity, schema, dedup, redaction
│   │   ├── controllers/
│   │   │   └── class-endpoints.php                — REST API route registration
│   │   ├── helpers/
│   │   │   ├── class-wp-error-handler.php         — Error capture (shutdown + exception)
│   │   │   ├── class-settings.php                 — Settings integration
│   │   │   ├── class-ajax-helper.php              — AJAX CSV export handler
│   │   │   └── class-miscellaneous.php            — Admin bar links, page helpers
│   │   └── settings/
│   │       └── settings-options/
│   │           └── fatals-list.php                — Module settings fields
│   └── migration/
│       └── class-migration.php                    — DB migrations (indexes, colors)
└── js/
    └── admin-export-csv.js                        — CSV export with progress & cancellation

 

3. Admin Screens

3.1 PHP Error List

URL wp-admin/admin.php?page=advan_fatals
Menu Position Sub-menu under “Error Logs” (position 1)
Capability manage_options (or read if menu_admins_only disabled)
Controller Fatals_View::analytics_fatals_page()
List Table Fatals_List (extends Abstract_List)

UI Components

  • Search box — searches across all columns using LIKE %term%
  • Plugin filter dropdown — filters errors by source plugin slug
  • “CSV Export” button — exports error data with progress bar and cancel option
  • Sortable columns — all columns sortable, default sort by datetime DESC
  • Row actions — View (modal) | Delete
  • Bulk actions — Delete selected records
  • View modal — full error detail with copy-to-clipboard and share
  • Stack trace — collapsible details with source file links (ThickBox)
  • Table metadata bar — size, engine, auto-increment, collation, create/update times
  • Severity badges — colored indicators for error severity
  • Relative timestamps — “5 minutes ago”, “Yesterday at 3:00 pm”
  • User links — clickable links to WordPress user profiles
Screen layout:
TEXT
┌──────────────────────────────────────────────────────────────────────┐
│  PHP errors                                                          │
│──────────────────────────────────────────────────────────────────────│
│  Bulk Actions [▼] [Apply]  [Plugin Filter ▼]  [CSV Export]           │
│  Size: 2.5 MB | Engine: InnoDB | Auto increment: 1542                │
│                                                          [🔍 Search] │
│──────────────────────────────────────────────────────────────────────│
│  ☐ Date ↕       | Severity | Message         | File      | Source    │
│  ☐ 5 min ago    | FATAL    | Call to undef…  | plugin.…  | MyPlugin  │
│     View | Delete                                                    │
│  ☐ 1 hour ago   | WARNING  | Undefined var…  | theme.…   | MyTheme   │
│     View | Delete                                                    │
│──────────────────────────────────────────────────────────────────────│
│  Bulk Actions [▼] [Apply]                            ‹ 1 of 50 ›     │
└──────────────────────────────────────────────────────────────────────┘

3.2 Module Settings

URL wp-admin/admin.php?page=advan_logs_settings
Settings File classes/vendor/settings/settings-options/fatals-list.php

Available Settings

Setting ID Type Default Description
Enable PHP errors list module fatals_module_enabled checkbox true Enables/disables the entire PHP Error Tracker module. When disabled, the sub-menu is hidden, no errors are captured, and no table operations are accessible.

4. Core Classes

4.1 ADVAN\Lists\Fatals_List

Extends Abstract_List (which extends WP_List_Table). Uses List_Trait. Handles the PHP error data admin list rendering, column management, sorting, searching, pagination, plugin filtering, bulk operations, CSV export, and table metadata display.

Constants

PHP
<?php
public const PAGE_SLUG            = '{ADVAN_INNER_SLUG}_page_advan_fatals';
public const SCREEN_OPTIONS_SLUG  = 'advanced_analytics_fatals_list';
public const SEARCH_INPUT         = 's';
public const FATALS_MENU_SLUG     = 'advan_fatals';
public const PLUGIN_FILTER_ACTION = self::PAGE_SLUG . '_filter_plugin';
protected const MAX_STACK_TRACE_LINES = 50;

Constructor

PHP
<?php
public function __construct( string $table_name = '' )

Initializes Common_Table with the fatals entity table name and calls the parent constructor with plural/singular labels set to the entity table name.

Key Methods

Method Description
init() Registers admin_post handler for the plugin filter action
truncate_fatals_table() Static. Truncates the fatals table (used by CRON scheduled cleanup)
menu_add() Registers the “PHP error viewer” submenu page under Error Logs (position 1). Sets up screen options, column management, help tabs, and action processing
process_actions_load() Runs on load-{hook} phase to handle bulk/row delete before output. Guards with manage_options
prepare_items() Queries the database with search, plugin filter, sorting, and pagination. Validates orderby/order parameters
fetch_table_data(array $args) Builds and executes SQL with search (LIKE across all columns), plugin slug filter, sort, and pagination. Counts total rows
filter_table_data($data, $key) In-memory PHP-side filter using stripos()
get_columns() Returns columns from manage_columns()
get_sortable_columns() Makes all admin columns sortable (derived from entity column info)
column_default($item, $column_name) Renders each column cell with specialized rendering per type (see Column Rendering below)
column_cb($item) Renders checkbox for bulk selection
get_bulk_actions() Returns ['delete' => 'Delete Records']
handle_table_actions() Processes single and bulk delete with nonce verification and redirect
extra_tablenav($which) Renders plugin filter dropdown, CSV Export button, and table metadata bar (size, engine, auto-increment, collation, timestamps)
manage_columns($columns) Static. Merges checkbox + entity admin columns. Cached in $admin_columns
single_row($item) Outputs <tr> with CSS class from fatal_status for row-level styling
display_tablenav($which) Renders nonce field, severity border styles, bulk actions, and pagination

Column Rendering

Column Rendering Logic
datetime Relative time (“5 minutes ago”), formatted date/time with timezone, row actions (View, Delete)
user_id Linked user display name + email, or “WP System or Anonymous user” for 0
message Error message with copy/share icons, collapsible stack trace with source file ThickBox links (max 50 lines)
error_file Clickable ThickBox link to view source file at the error line
ip Comma-separated IPs rendered on separate lines
severity, type_env, user_roles, version_text, source_type, repeating Bold text
source Bold plugin/theme/core name, or “Unknown”

4.2 ADVAN\Lists\Views\Fatals_View

Handles page rendering for the PHP error list screen, the view modal, and processes form submissions. All methods are static.

Public Static Methods

Method Description
analytics_fatals_page() Main page renderer. Enforces manage_options capability. Enqueues ThickBox, media-views, and wp-api-fetch. Renders search box, list table, modal dialog, and inline JavaScript for REST API calls, clipboard copy, Web Share API, and dark skin support
add_help_content_table() Returns help tab content — overview of module capabilities and usage instructions
add_config_content_table() Returns config panel with table metadata (name, engine, version, create time, collation), Truncate Table button, and Drop Table button (if not WP core table). Both use REST API endpoints
page_load() Removes _wp_http_referer and bulk_action from URL on page load to keep URLs clean
plugin_filter_action() Handles plugin filter form submission. Verifies nonce, sanitizes plugin slug, supports multisite network admin context, and redirects with plugin filter parameter

The View action triggers a REST API call via wp.apiFetch() to retrieve full error data. The response HTML is injected into the modal overlay. The modal also supports:

  • Copy to clipboard — copies raw HTML of error data via navigator.clipboard
  • Share — uses the navigator.share Web Share API (falls back gracefully)
  • Dark skin — reads aadvana-backend-skin from localStorage
  • Source file links — ThickBox links open within the modal for viewing source code

4.3 ADVAN\Entities\WP_Fatals_Entity

Extends Abstract_Entity. Central entity class for all fatals database operations. Handles table creation, schema definition, deduplication, PII redaction, source identification, IP collection, and record preparation. Contains both static and instance methods.

Constants

PHP
<?php
// Table name: {prefix}advan_wp_fatals_log
protected static $table = ADVAN_PREFIX . 'wp_fatals_log';

Key Methods

Method Return Description
create_table(?$connection) bool Creates the fatals DB table with full schema including indexes
get_column_names_admin() array Returns 12 columns visible in the admin list (+ blog_id on multisite)
get_details_columns() array Returns 14 columns shown in the row detail modal (includes error_line and backtrace_segment)
hash_generating(string) string SHA-256 hash generation
redact_text(string) string Redacts Bearer tokens, JWTs, API keys, emails, long hex strings, sensitive URL params
redact_backtrace($backtrace) mixed Recursively redacts backtrace array structures
normalize_for_hash(string, $bt, string, $line) string Normalizes timestamps, line numbers, large numbers for dedup hashing
prepare_fatality_to_store(array) array Core method. Redacts, hashes, deduplicates (increments repeating), identifies source, collects IP & user data, inserts into DB
collect_all_client_ips(bool) array Collects IPs from 12+ server headers; supports filtering, anonymization, hashing modes
anonymize_ip(string) string Zeros last octet (IPv4) or lower 80 bits (IPv6)
version_to_decimal(string) int Encodes semver to sortable integer (major * 1e12 + minor * 1e6 + patch)
alter_table_470() bool Migration: adds severity, source_slug, source_type indexes
prune_old_records(int) int Deletes records older than retention period (default 90 days)
get_all_plugins_dropdown($selected, $which) string Renders <select> dropdown of plugins with recorded errors

4.4 ADVAN\Helpers\WP_Error_Handler

Handles PHP error capture via three entry points. All capture is gated by the fatals_module_enabled setting.

Error Capture Entry Points

Method Trigger Description
shutdown() PHP shutdown function Captures error_get_last(). For E_ERROR/E_PARSE: sends Slack/Telegram notifications and generates recovery mode URL. For all non-null errors: stores via prepare_fatality_to_store()
exception_handler($e) Uncaught exception/error Logs formatted stack trace to error_log. Calls prepare_fatality_to_store() with severity 'FATAL' and $e->getTrace() as backtrace
handle_error() Custom error handler Handles general PHP error logging with stack traces (does not directly store to fatals table)

5. Database Schema

Table name: {prefix}advan_wp_fatals_log

Column Type Default Notes
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
hash_key CHAR(64) NOT NULL UNIQUE KEY, SHA-256 dedup hash
blog_id INT NOT NULL Multisite blog ID
datetime BIGINT NOT NULL 0 Unix timestamp
severity VARCHAR(50) NULL e.g. FATAL, WARNING, PARSE, DEPRECATED
message MEDIUMTEXT NULL Redacted error message
error_file VARCHAR(255) NULL File path where error occurred
error_line INT NULL Line number
backtrace_segment MEDIUMTEXT NOT NULL JSON-encoded stack trace
user_id BIGINT UNSIGNED 0 WordPress user ID
user_roles VARCHAR(155) NULL Comma-separated roles
ip TEXT NULL Client IP(s), supports anonymization/hashing
type_env VARCHAR(20) "" Environment type (admin, ajax, cron, rest, cli, etc.)
source_type VARCHAR(20) NULL plugin, theme, core, or php
source VARCHAR(255) NULL Plugin/theme/WordPress name
source_slug VARCHAR(255) NULL Plugin slug for filtering
version_text VARCHAR(19) NULL Human-readable version
version BIGINT UNSIGNED NULL Sortable decimal-encoded version
repeating INT NOT NULL 1 Occurrence count (dedup counter)

Indexes

Index Type Column(s)
PRIMARY PRIMARY KEY id
hash_key UNIQUE hash_key
datetime KEY datetime
severity KEY severity
source_slug KEY source_slug
source_type KEY source_type

6. Error Capture & Deduplication

Capture Flow

  1. PHP error occurs (fatal, exception, warning, etc.)
  2. WP_Error_Handler captures the error via shutdown function or exception handler
  3. WP_Fatals_Entity::prepare_fatality_to_store() is called with error details
  4. Message and backtrace are redacted of PII/secrets
  5. A normalized hash is generated from the error signature
  6. The hash is checked against existing records
  7. If a matching hash exists: repeating count is incremented, datetime updated
  8. If no match: a new record is inserted with source identification and user context

Deduplication Logic

Errors are deduplicated via SHA-256 hash of a normalized string: message|line|file|backtrace. The normalization process:

  • Timestamps are replaced with [TS]
  • Line numbers are replaced with line [N]
  • Large numbers are replaced with [N]
  • Hex values are replaced with 0x[HEX]

This ensures that the same fundamental error with different runtime details (e.g., different timestamps or line numbers from dynamic code) is recognized as a single issue.

7. Source Detection

prepare_fatality_to_store() identifies error sources in priority order:

Priority Detection Method source_type source
1 Plugin_Theme_Helper::get_plugin_from_file_path() plugin Plugin name
2 Plugin_Theme_Helper::get_theme_from_file_path() theme Theme name
3 File path contains ABSPATH . WPINC core WordPress
4 Fallback php PHP

Version information is also extracted from the identified source and stored both as human-readable text (version_text) and a sortable integer (version) using the version_to_decimal() encoding scheme (major * 10^12 + minor * 10^6 + patch).

8. PII & Secret Redaction

Before any error data is stored in the database, the redact_text() method sanitizes messages and the redact_backtrace() method sanitizes stack traces. The following patterns are redacted:

  • Bearer tokensBearer ... replaced with Bearer [REDACTED]
  • JWT tokens — three-part dot-separated base64 strings
  • API keys — common key patterns and variable names containing key, secret, password, token
  • Email addresses — replaced with [EMAIL]
  • Long hex strings — potential hashes or tokens
  • Sensitive URL parameters — passwords, tokens, and keys in query strings
Extensibility: The advan_redact_text filter allows external plugins to add custom redaction rules to the pipeline.

9. REST API Endpoints

All endpoints are registered under the 0-day/v1 namespace. Every endpoint requires manage_options capability.

View Error Record GET

Route /0-day/v1/get_fatals_record/{table_name}/{id}/
Method GET
Handler Common_Table::extract_fatals_row_data()
Parameters
  • table_name (string, required) — must match WP_Fatals_Entity::get_table_name()
  • id (string, required) — record ID
Validation Table name must exactly match the fatals entity table name. Table existence verified. Double capability check.
Response { success: true, mail_body: "<html>..." } — HTML table with detail columns, formatted datetime, source file ThickBox links, and formatted backtrace via Requests_List::format_trace()

Truncate Table DELETE

Route /0-day/v1/truncate_table/{table_name}/
Method DELETE
Handler Common_Table::truncate_table()
Parameters table_name (string, required)
Response { success: true }
Errors 400 if core table, 403 if insufficient permissions

Drop Table DELETE

Route /0-day/v1/drop_table/{table_name}/
Method DELETE
Handler Common_Table::drop_table()
Parameters table_name (string, required)
Response { success: true }
Errors 400 if core table, 403 if insufficient permissions

10. Hooks, Actions & Filters

Admin Post Actions ACTION

Action Handler Description
admin_post_{PLUGIN_FILTER_ACTION} Fatals_View::plugin_filter_action Filter error list by plugin slug

WordPress Hooks Used ACTION

Hook Priority Description
load-{page_slug} default Common help tabs via Settings::aadvana_common_help
load-{page_slug} default Processes bulk/row actions before output via process_actions_load
manage_{hook}_columns default Registers column definitions via manage_columns

Filters FILTER

Filter Default Description
advan_redact_text passthrough Allows external plugins to add custom redaction rules to error text
advan_ip_filter_private false Whether to exclude private/reserved/loopback IPs from collection
advan_ip_header_keys 12 header keys Customize which server headers to read IPs from
advan_ip_trust_proxy false Whether to trust proxy headers (if false, only REMOTE_ADDR is used)
advan_ip_mode 'raw' IP storage mode: raw, anonymize, or hash
advan_ip_hash_salt '' Custom salt for IP hashing (falls back to wp_salt('auth'))

11. Settings Reference

Settings are on the PHP error Log tab within the main settings page.

PHP
<?php
// Check if the PHP Error Tracker module is enabled
$enabled = Settings::get_option( 'fatals_module_enabled' );

Settings Builder Usage

PHP
<?php
// How the settings are defined in fatals-list.php
Settings::build_option(
    array(
        'title' => esc_html__( 'PHP errors list options', '0-day-analytics' ),
        'id'    => 'fatals-settings-options',
        'type'  => 'header',
        'hint'  => esc_html__( 'The module captures PHP Fatal Errors...', '0-day-analytics' ),
    )
);

Settings::build_option(
    array(
        'name'    => esc_html__( 'Enable PHP errors list module', '0-day-analytics' ),
        'id'      => 'fatals_module_enabled',
        'type'    => 'checkbox',
        'hint'    => esc_html__( 'If you disable this, the entire plugin fatals module will be disabled...', '0-day-analytics' ),
        'default' => Settings::get_option( 'fatals_module_enabled' ),
    )
);

12. List Table Columns & Sorting

Admin Columns

Key Header Sortable Description
cb No Bulk selection checkbox
datetime Date Yes Timestamp with relative time and row actions
severity Severity Yes Error severity level (FATAL, WARNING, etc.)
message Message Yes Error message with stack trace toggle
error_file File Yes Source file with ThickBox link
source_type Source Type Yes plugin / theme / core / php
source Source Yes Name of the plugin/theme/core
version_text Version Yes Plugin/theme version string
type_env Environment Yes admin, ajax, cron, rest, cli, etc.
user_id User Yes WordPress user who triggered the error
user_roles User Role(s) Yes Comma-separated WordPress roles
ip IP Yes Client IP address(es)
repeating Number of occurrences Yes Deduplication counter
blog_id From Blog Yes Multisite only — originating blog

The search box filters across all columns using LIKE %term% for each column (OR logic). Query parameter: s

Plugin Filter

A dropdown of plugins that have recorded errors. Filters by source_slug column. Submitted via admin_post handler with nonce verification.

Default Sort

By datetime column in DESC order (newest first).

Pagination

Default items per page: 20. Configurable via Screen Options. Uses LIMIT/OFFSET SQL pagination.

13. Bulk & Row Actions

Row Actions

Action Method Description
View REST API (AJAX modal) Opens modal showing full error data including backtrace via wp.apiFetch()
Delete Page redirect Deletes the record after JavaScript confirm() dialog

Bulk Actions

Action Description
Delete Records Permanently delete all selected error records

Destructive Table Actions (Config Help Tab)

Action Method Core Tables Description
Truncate Table REST API (DELETE) Blocked Removes all error records, keeps structure. JavaScript confirm required
Drop Table REST API (DELETE) Hidden Permanently removes error log table and data. JavaScript confirm required

14. CSV Export

The CSV export functionality is handled via AJAX through Ajax_Helper. When the export type is fatals:

  • A new Fatals_List instance is created
  • Active search term and plugin filter are passed from the UI
  • fetch_table_data() is called with batch pagination
  • Data is exported through the shared CSV export pipeline
  • The file name includes the fatals table name
  • Progress is reported via AJAX callbacks with progress bar and cancel support

15. Security Model

Capability Checks

  • manage_options enforced on: page rendering, row delete, bulk operations, REST API endpoints, action processing
  • Menu visibility: manage_options or read depending on menu_admins_only setting

Nonce Verification

Context Nonce Action
Plugin filter {PLUGIN_FILTER_ACTION} / nonce field: {PLUGIN_FILTER_ACTION}nonce
Source file viewing source-view
Bulk delete bulk-{table_name} (WP_List_Table auto-generated)
Single delete bulk-{table_name} (shared with bulk)

Input Validation

  • Plugin slugs — validated with /^[a-zA-Z0-9\-_]{1,255}$/ regex
  • Order/orderby — sanitized via esc_sql(), sanitize_text_field(), and allowlisted
  • Search terms — escaped via $wpdb->esc_like() and parameterized with %s
  • Record IDs — cast to (int) before delete operations
  • All displayed values — escaped with esc_html(), esc_attr(), esc_url()

PII Protection

  • Error messages redacted of secrets and PII before storage
  • Stack traces recursively redacted
  • IP addresses support anonymization and hashing modes
  • Custom redaction rules via advan_redact_text filter

16. Severity Mapping

PHP error codes are mapped to human-readable severity strings by WP_Error_Handler::error_code_to_string():

PHP Constant Code Severity String
E_ERROR 1 FATAL
E_WARNING 2 WARNING
E_PARSE 4 PARSE
E_NOTICE 8 NOTICE
E_CORE_ERROR 16 CORE ERROR
E_CORE_WARNING 32 CORE WARNING
E_COMPILE_ERROR 64 COMPILE ERROR
E_COMPILE_WARNING 128 COMPILE WARNING
E_USER_ERROR 256 USER ERROR
E_USER_WARNING 512 USER WARNING
E_USER_NOTICE 1024 USER NOTICE
E_STRICT 2048 STRICT
E_RECOVERABLE_ERROR 4096 RECOVERABLE ERROR
E_DEPRECATED 8192 DEPRECATED
E_USER_DEPRECATED 16384 USER DEPRECATED

Uncaught exceptions handled via exception_handler() are always stored with severity FATAL.

17. IP Address Handling

WP_Fatals_Entity::collect_all_client_ips() collects client IPs from multiple server headers and supports three configurable storage modes:

Mode Filter Value Behavior
Raw raw IPs stored as-is
Anonymized anonymize Last octet zeroed (IPv4) or lower 80 bits zeroed (IPv6)
Hashed hash SHA-256 hash with configurable salt (defaults to wp_salt('auth'))

Header Sources

By default, the following headers are checked (configurable via advan_ip_header_keys filter):

  • HTTP_CF_CONNECTING_IP (Cloudflare)
  • HTTP_TRUE_CLIENT_IP
  • HTTP_X_FORWARDED_FOR
  • HTTP_X_REAL_IP
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_FORWARDED
  • HTTP_X_FORWARDED
  • HTTP_CLIENT_IP
  • HTTP_FASTLY_CLIENT_IP
  • HTTP_AKAMAI_ORIGIN_HOP
  • HTTP_X_APPENGINE_USER_IP
  • REMOTE_ADDR
Security: When advan_ip_trust_proxy is false (default), only REMOTE_ADDR is used regardless of other headers. This prevents IP spoofing via forged proxy headers.

18. Code Examples

Example 1: Check If the Fatals Module Is Enabled

PHP
<?php
use ADVAN\Helpers\Settings;

if ( Settings::get_option( 'fatals_module_enabled' ) ) {
    echo 'PHP Error Tracker is active.';
}

Example 2: Query Fatals by Severity

PHP
<?php
use ADVAN\Entities\WP_Fatals_Entity;

// Get all FATAL severity records from the last 24 hours
global $wpdb;
$table  = WP_Fatals_Entity::get_table_name();
$since  = time() - DAY_IN_SECONDS;

$fatals = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT id, message, error_file, error_line, source, datetime
         FROM {$table}
         WHERE severity = %s AND datetime > %d
         ORDER BY datetime DESC",
        'FATAL',
        $since
    ),
    ARRAY_A
);

foreach ( $fatals as $fatal ) {
    printf(
        "ID: %d | Source: %s | File: %s:%d\nMessage: %s\n\n",
        $fatal['id'],
        $fatal['source'] ?? 'Unknown',
        $fatal['error_file'],
        $fatal['error_line'],
        $fatal['message']
    );
}

Example 3: Add Custom PII Redaction Rules

PHP
<?php
// In your plugin or theme functions.php
add_filter( 'advan_redact_text', function( string $text ): string {
    // Redact custom internal API tokens
    $text = preg_replace(
        '/MYAPP-[A-Za-z0-9]{32}/',
        '[MYAPP-TOKEN-REDACTED]',
        $text
    );
    return $text;
} );

Example 4: Configure IP Anonymization

PHP
<?php
// Anonymize all stored IPs (GDPR compliance)
add_filter( 'advan_ip_mode', function() {
    return 'anonymize';
} );

// Or hash them instead
add_filter( 'advan_ip_mode', function() {
    return 'hash';
} );

// Custom hash salt
add_filter( 'advan_ip_hash_salt', function() {
    return 'my-custom-salt-value';
} );

Example 5: Trust Proxy Headers (When Behind a Load Balancer)

PHP
<?php
// Enable proxy header trust (only if you control the proxy)
add_filter( 'advan_ip_trust_proxy', '__return_true' );

// Filter private IPs from the collection
add_filter( 'advan_ip_filter_private', '__return_true' );

Example 6: Prune Old Error Records

PHP
<?php
use ADVAN\Entities\WP_Fatals_Entity;

// Delete records older than 30 days
$deleted = WP_Fatals_Entity::prune_old_records( 30 );

echo "Pruned {$deleted} old error records.";

Example 7: Get Plugin Filter Dropdown

PHP
<?php
use ADVAN\Entities\WP_Fatals_Entity;

// Render a dropdown of plugins that have recorded errors
$selected_plugin = 'my-plugin-slug';
$dropdown_html   = WP_Fatals_Entity::get_all_plugins_dropdown( $selected_plugin );

echo $dropdown_html;

Example 8: Inspect the Fatals Table Schema

PHP
<?php
use ADVAN\Entities_Global\Common_Table;
use ADVAN\Entities\WP_Fatals_Entity;

Common_Table::init( WP_Fatals_Entity::get_table_name() );

$columns = Common_Table::get_columns_info();

foreach ( $columns as $col ) {
    printf(
        "Column: %s | Type: %s | Key: %s\n",
        $col['Field'],
        $col['Type'],
        $col['Key']
    );
}

Example 9: Get Fatals Table Health Info

PHP
<?php
use ADVAN\Entities_Global\Common_Table;
use ADVAN\Entities\WP_Fatals_Entity;

$info = Common_Table::get_table_info( WP_Fatals_Entity::get_table_name() );

if ( ! is_wp_error( $info ) ) {
    echo 'Row count: ' . $info['health']['row_count'];
    echo 'Data size: ' . size_format( $info['health']['data_size'] );
    echo 'Needs optimization: ' . ( $info['health']['needs_optimization'] ? 'Yes' : 'No' );
}

Example 10: Version Encoding

PHP
<?php
use ADVAN\Entities\WP_Fatals_Entity;

// Convert semantic version to sortable integer
$version_int = WP_Fatals_Entity::version_to_decimal( '2.4.1' );
// Result: 2000000004000001

// This allows sorting by version in SQL:
// ORDER BY version DESC

Need User Guide documentation?
See PHP Error Module User Guide for more details about configuration, practical usage and information.

← PHP Error Module — User Guide Performance Module — User Guide →
Share this page
Back to top