0 Day Analytics – Requests Module Developer Documentation

Table of Contents

1. Overview & Architecture

The Requests Module provides comprehensive monitoring and logging of all HTTP API requests (outgoing wp_remote_* calls) and incoming REST API requests on a WordPress site. It stores every captured request in a dedicated database table and presents them via a WP_List_Table-based admin interface with analytics dashboard, filtering, searching, and export capabilities.

Key Capabilities

  • Intercept and log all outgoing HTTP API requests via pre_http_request and http_api_debug hooks
  • Intercept and log all incoming REST API requests via rest_pre_dispatch and rest_request_after_callbacks hooks
  • Automatic identification of the originating plugin/theme via PHP stack trace analysis
  • Full request/response capture with automatic sensitive data redaction
  • Analytics dashboard with totals, error rates, top domains, and performance trends
  • Advanced filtering by status, type, plugin, domain, date range, and runtime range
  • CSV export with filter context preservation
  • Toggle HTTP/REST monitoring independently via REST API
  • Automatic cleanup via configurable cron schedule
  • Table management (truncate/drop) via REST API

Technology Stack

  • PHP 7.4+ (strict types)
  • WordPress WP_List_Table API
  • WordPress wp-api-fetch for REST interactions
  • Custom database table with optimised indexes
  • jQuery for modal interactions, vanilla JS for table management

2. File Map


advanced-analytics/
├── classes/
│   └── vendor/
│       ├── controllers/
│       │   ├── class-requests-log.php        — Request capture (HTTP + REST hooks)
│       │   └── api/
│       │       └── class-endpoints.php       — REST API registration
│       ├── lists/
│       │   ├── class-requests-list.php       — WP_List_Table for requests display
│       │   └── views/
│       │       └── class-requests-view.php   — Page rendering, modal, analytics
│       ├── helpers/
│       │   ├── class-ajax-helper.php         — AJAX endpoints (CSV export)
│       │   └── class-plugin-theme-helper.php — Plugin identification from file paths
│       ├── entities/
│       │   └── class-requests-log-entity.php — DB entity, schema, migrations
│       ├── settings/
│       │   └── settings-options/
│       │       └── request-list.php          — Settings form fields
│       └── checks/
│           └── speed/
│               └── class-external-requests-check.php — Performance audit
└── assets/
    ├── css/                                  — Stylesheets
    └── js/                                   — JavaScript files

3. Admin Screens

3.1 Requests List

URL wp-admin/admin.php?page=advan_requests
Menu Position Sub-menu under “Error Logs” (position 6)
Capability manage_options (or read if menu_admins_only is disabled)
Controller Requests_View::analytics_requests_page()
List Table Requests_List (extends Abstract_ListWP_List_Table)

UI Components

  • Status notices — Warnings when logging or HTTP/REST monitoring is disabled
  • Analytics dashboard — Summary cards, status/type breakdowns, top domains, trend table
  • Filter controls — Plugin, status, type, date range, domain, runtime range dropdowns and inputs
  • Search box — Full-text search across all columns (input name: s)
  • Sortable columns — Date, Type, Plugin, Status, URL, Page, Domain, User, Runtime
  • Pagination — Configurable via screen options
  • Row actions — Delete | Details (per row)
  • Bulk actions — Delete Records (for selected rows)
  • CSV Export — Export current filtered view to CSV
  • Table management — Truncate / Drop table controls (via help panel)
Screen layout:

┌──────────────────────────────────────────────────────────────┐
│  Requests                                                    │
│──────────────────────────────────────────────────────────────│
│  ⚠ Status notices (if logging/monitoring disabled)           │
│──────────────────────────────────────────────────────────────│
│  ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌────────┐ ┌──────┐   │
│  │  Total  │ │ Last 24h │ │ Last 7d  │ │Avg Time│ │Errors│   │
│  └─────────┘ └──────────┘ └──────────┘ └────────┘ └──────┘   │
│  By Status | By Type | Top 10 Domains | 30-Day Trends        │
│──────────────────────────────────────────────────────────────│
│  [Plugin ▼][Status ▼][Type ▼][From][To][Domain][Min][Max]    │
│  [Filter] [Clear Filters]              [CSV Export] [🔍]     │
│──────────────────────────────────────────────────────────────│
│  ☐ Date ↕ | Type ↕ | Plugin ↕ | Status ↕ | URL ↕ | ...       │
│  ☐ 2026.. | admin  | woo..    | success  | https..| ...      │
│     Delete | Details                                         │
│──────────────────────────────────────────────────────────────│
│  Bulk Actions [▼] [Apply]               ‹ 1 of 5 ›           │
└──────────────────────────────────────────────────────────────┘

3.2 Request Details Modal

Trigger Click “Details” row action on any request entry
Implementation jQuery-powered modal overlay using WordPress media-modal CSS classes
Data Source Hidden HTML elements embedded in each row (#advana-request-details-{id}, #advana-response-details-{id})
  • Header — Request type, status badge, runtime, domain
  • URLs — Page URL (origin) and Request URL (target)
  • Request panel — JSON-formatted request arguments with copy/share buttons
  • Response panel — JSON-formatted response summary with copy/share buttons
  • Stack trace — Full PHP call stack that triggered the request

3.3 Module Settings

URL wp-admin/admin.php?page=advan_logs_settings#aadvana-options-tab-request-list
Settings File classes/vendor/settings/settings-options/request-list.php

Available Settings

Setting ID Type Description
Enable requests module requests_module_enabled checkbox Master toggle for the entire requests module. Controls menu visibility and all request logging.
Enable requests logging advana_requests_enable checkbox Controls active request interception. When disabled, the viewer remains accessible but no new data is captured.
Disable HTTP Requests logging advana_http_requests_disable checkbox Stops capturing outgoing HTTP API requests (wp_remote_*). REST API logging is unaffected.
Disable REST API Requests logging advana_rest_requests_disable checkbox Stops capturing incoming REST API requests. HTTP API logging is unaffected.
Clear requests table every advana_rest_requests_clear select Automatic cleanup schedule. Options: Never (-1), Hourly, Twice Daily, Daily, Weekly, or any custom schedule. Registers a WordPress cron job.
Warning: The auto-cleanup cron truncates the entire requests table — it does not selectively remove old records.

4. Core Classes

4.1 ADVAN\Controllers\Requests_Log

Core request capture controller. Hooks into WordPress HTTP API and REST API lifecycle to intercept and log every request. Uses the Controller_Init_Trait for conditional initialisation based on settings.

Initialisation Flow

PHP
<?php
// 1. Check master toggle
if ( Settings::get_option( 'requests_module_enabled' ) ) {
    // 2. Check logging toggle via conditional_init()
    static::conditional_init( 'advana_requests_enable', function() {
        // 3. Register HTTP hooks (if not disabled)
        if ( ! Settings::get_option( 'advana_http_requests_disable' ) ) {
            add_filter( 'pre_http_request', [ __CLASS__, 'pre_http_request' ], 0, 3 );
            add_action( 'http_api_debug', [ __CLASS__, 'capture_request' ], 10, 5 );
        }
        // 4. Register REST hooks (if not disabled)
        if ( ! Settings::get_option( 'advana_rest_requests_disable' ) ) {
            add_filter( 'rest_pre_dispatch', [ __CLASS__, 'pre_http_request' ], 0, 3 );
            add_filter( 'rest_request_after_callbacks', [ __CLASS__, 'capture_rest_request' ], 10, 3 );
        }
    });
}

Properties

Property Type Description
$requests int (static) Running counter of requests captured during the current page load
$last_id int (static) ID of the last inserted log entry (used for request chaining)
$page_url string (static) Cached originating page URL
$trace string (static) Cached JSON-encoded PHP stack trace

HTTP Request Capture Methods

Method Hook Description
pre_http_request($response, $args, $url) pre_http_request (priority 0) Starts the timer by setting $_SERVER['REQUEST_TIME_FLOAT']
capture_request($response, $context, $class, $args, $url) http_api_debug (priority 10) Captures the full HTTP request/response and stores it in the database

REST Request Capture Methods

Method Hook Description
pre_http_request($response, $args, $url) rest_pre_dispatch (priority 0) Starts the timer (same method reused)
capture_rest_request($response, $handler, $request) rest_request_after_callbacks (priority 10) Captures REST request route, attributes, response and stores in database

Utility Methods

Method Return Description
current_page_type() string Determines the request context: cron, ajax, rest_api, xmlrpc, wp-cli, login, frontend, admin, core, installing, activate, or undetermined
page_url() string Builds and sanitises the current page URL from server variables
get_trace() string Returns a JSON-encoded PHP stack trace (cached per request)
sanitize_request_args(array $args) array Redacts sensitive headers/keys, truncates large values
sanitize_response($response) string Extracts a safe summary from the HTTP/REST response with size limits
sanitize_url(string $url) string Strips sensitive query parameters from URLs before logging

4.2 ADVAN\Lists\Requests_List

Extends Abstract_List (which extends WP_List_Table). Handles the requests admin list table rendering, column management, sorting, searching, filtering, bulk operations, CSV export, and the monitoring toggle REST endpoint.

Constants

PHP
<?php
const PAGE_SLUG             = ADVAN_INNER_SLUG . '_page_advan_requests';
const SCREEN_OPTIONS_SLUG   = 'advanced_analytics_requests_list';
const SEARCH_INPUT          = 's';
const REQUESTS_MENU_SLUG    = 'advan_requests';
const PLUGIN_FILTER_ACTION  = self::PAGE_SLUG . '_filter_plugin';

Key Methods

Method Description
init() Registers cron hooks and admin_post filter action
add_cron_job($crons) Registers the auto-truncate cron (advan_request_table_clear) based on the advana_rest_requests_clear setting
truncate_requests_table() Cron callback — truncates the requests log table
menu_add() Registers the admin submenu page, screen options, and column filter
process_actions_load() Processes bulk actions on load-{page} hook (before output)
prepare_items() Populates the table: parses filters, builds SQL query, retrieves results
fetch_table_data($args) Builds and executes parameterised SQL with all filter conditions
manage_columns($columns) Defines visible columns for the list table
get_sortable_columns() Returns all sortable columns (all entity columns are sortable)
get_bulk_actions() Returns available bulk actions (Delete Records)
handle_table_actions() Processes bulk delete after nonce and capability verification
set_request_status($request) REST endpoint callback to toggle HTTP/REST monitoring on/off

4.3 ADVAN\Lists\Views\Requests_View

Handles page rendering for the requests list screen, the details modal, analytics dashboard, and form processing.

Key Methods

Method Description
analytics_requests_page() Entry point — calls display_page() from parent with permission message
render_page_content() Renders status notices, analytics dashboard, filter form, list table, and modal HTML
render_analytics_dashboard($data) Renders summary cards, status/type breakdowns, top domains, and trend table
get_analytics_data() Queries the database for analytics: totals, status counts, type counts, averages, top domains, daily trends
plugin_filter_action() Handles plugin filter dropdown form submission and redirect
add_help_content_table() Returns help tab content string
add_config_content_table() Returns table info panel with truncate/drop controls

4.4 ADVAN\Entities\Requests_Log_Entity

Database entity class for the requests log table. Extends Abstract_Entity and defines the table schema, column types, default values, creation SQL, and migration methods.

Table Name

PHP
<?php
protected static $table = ADVAN_PREFIX . 'requests_log';
// Resolves to: {wp_prefix}advan_requests_log

Fields Definition

Field PHP Type DB Type Default
id int BIGINT unsigned AUTO_INCREMENT
type string VARCHAR(20) ""
plugin string VARCHAR(200) ""
url string TEXT(2048) ""
page_url string TEXT(2048) ""
domain string VARCHAR(255) NULL
user_id int BIGINT unsigned 0
runtime float DECIMAL(10,3) 0
request_status string VARCHAR(20) ""
request_group string VARCHAR(20) ""
request_source string VARCHAR(255) ""
request_args string MEDIUMTEXT ""
response string MEDIUMTEXT ""
date_added string DOUBLE 0
requests int SMALLINT unsigned 0
trace string MEDIUMTEXT ""

Database Indexes

Index Name Columns Purpose
PRIMARY id Primary key
runtime runtime Runtime range filtering and sorting
idx_date_status date_added, request_status(10) Date range + status combined filtering
idx_plugin_type plugin(50), type Plugin + type combined filtering
idx_domain domain(50) Domain filtering
idx_user_id user_id User filtering
idx_runtime_status runtime, request_status(10) Performance + status queries

Migration Methods

Method Version Description
create_table() 2.4.2.1+ Creates the table with full schema and indexes
alter_table_393() 3.9.3 Adds the plugin column
alter_table_3931() 3.9.3.1 Changes domain column to allow NULL
alter_table_480() 4.8.0 Adds performance indexes (idempotent — checks existing indexes first)

5. Data Model & Database Schema

Each logged request is stored as a row in the {prefix}advan_requests_log table. The log entry is built inside the capture methods:

PHP
<?php
$log_entry = array(
    'url'            => 'https://api.wordpress.org/plugins/...',  // Target URL
    'page_url'       => 'https://example.com/wp-admin/...',       // Origin page
    'type'           => 'admin',                                   // Request context
    'domain'         => 'api.wordpress.org',                       // Extracted domain
    'user_id'        => 1,                                         // WP user ID (0 = anonymous)
    'runtime'        => 0.245,                                     // Seconds elapsed
    'request_status' => 'success',                                 // success | error | timeout
    'request_group'  => '',                                        // Optional grouping
    'request_source' => '',                                        // Optional source identifier
    'request_args'   => '{"method":"GET","timeout":10,...}',       // JSON (sanitised)
    'response'       => '{"response_code":200,"body_preview":"..."}', // JSON (sanitised)
    'date_added'     => 1711360000,                                // Unix timestamp
    'requests'       => 3,                                         // Nth request in this page load
    'trace'          => '[{"file":"...","line":42,...},...]',       // JSON stack trace
    'plugin'         => 'woocommerce',                             // Identified originating plugin
);

Create Table SQL

SQL
CREATE TABLE `{prefix}advan_requests_log` (
    id BIGINT unsigned NOT NULL AUTO_INCREMENT,
    type VARCHAR(20) NOT NULL DEFAULT "",
    plugin VARCHAR(200) NOT NULL DEFAULT "",
    url TEXT(2048),
    page_url TEXT(2048),
    user_id BIGINT unsigned NOT NULL DEFAULT 0,
    domain VARCHAR(255),
    runtime DECIMAL(10,3),
    request_status VARCHAR(20),
    request_group VARCHAR(20),
    request_source VARCHAR(255),
    request_args MEDIUMTEXT,
    response MEDIUMTEXT,
    date_added DOUBLE NOT NULL DEFAULT 0,
    requests SMALLINT unsigned NOT NULL DEFAULT 0,
    trace MEDIUMTEXT,
    PRIMARY KEY (id),
    KEY `runtime` (`runtime`),
    KEY `idx_date_status` (`date_added`, `request_status`(10)),
    KEY `idx_plugin_type` (`plugin`(50), `type`),
    KEY `idx_domain` (`domain`(50)),
    KEY `idx_user_id` (`user_id`),
    KEY `idx_runtime_status` (`runtime`, `request_status`(10))
);

6. Request Capture Flow

HTTP API Request Flow

  1. WordPress core calls wp_remote_get(), wp_remote_post(), or similar
  2. pre_http_request filter fires (priority 0) → Requests_Log::pre_http_request() records the start time
  3. WordPress HTTP transport executes the request
  4. http_api_debug action fires (priority 10) → Requests_Log::capture_request() captures URL, args, response, runtime, trace
  5. The log entry is sanitised (sensitive data redacted, values truncated) and inserted into the database via Requests_Log_Entity::insert()

REST API Request Flow

  1. An incoming REST API request is dispatched by rest_api_loaded()
  2. rest_pre_dispatch filter fires (priority 0) → Requests_Log::pre_http_request() records the start time
  3. WordPress dispatches the request to the matching route callback
  4. rest_request_after_callbacks filter fires (priority 10) → Requests_Log::capture_rest_request() captures route, attributes, response, runtime, trace
  5. The log entry is sanitised and inserted into the database

Plugin Identification

The originating plugin is identified by analysing the PHP stack trace. The 8th frame in the trace is inspected for a file path, which is then matched against known plugin directories using Plugin_Theme_Helper::get_plugin_from_file_path().

7. REST API Endpoints

Toggle HTTP/REST Monitoring GET

Endpoint /wp-json/0-day/v1/requests/{request_type}/{status}/
Method GET (WP_REST_Server::READABLE)
Permission manage_options capability
Parameters request_type (required) — http or rest
status (required) — enable or disable

Example: Disable HTTP monitoring

JavaScript
wp.apiFetch({
    path: '/0-day/v1/requests/http/disable/',
}).then(function(response) {
    console.log('HTTP monitoring disabled');
}).catch(function(err) {
    console.error('Failed:', err.message);
});

Example: Enable REST monitoring

JavaScript
wp.apiFetch({
    path: '/0-day/v1/requests/rest/enable/',
}).then(function(response) {
    console.log('REST monitoring enabled');
}).catch(function(err) {
    console.error('Failed:', err.message);
});

Truncate Table DELETE

Endpoint /wp-json/0-day/v1/truncate_table/{table_name}/
Method DELETE
Permission manage_options capability
Parameter table_name (required) — the full table name (e.g. wp_advan_requests_log)

Success Response

JSON
{
    "success": true
}

Drop Table DELETE

Endpoint /wp-json/0-day/v1/drop_table/{table_name}/
Method DELETE
Permission manage_options capability
Parameter table_name (required) — the full table name

Get Single Record GET

Endpoint /wp-json/0-day/v1/get_table_record/{table_name}/{id}/
Method GET
Permission manage_options capability
Parameters table_name (required) — the full table name
id (required) — the record ID

8. AJAX Handlers

The requests module uses generic AJAX handlers shared across the plugin.

CSV Export AJAX

Action wp_ajax_aadvana_export_large_csv
Handler Ajax_Helper::export_large_csv()
Trigger Set typeExport=requests in the POST data
Parameters All current filter values (search, plugin, date range, status, type, domain, runtime min/max)

The export respects the current filter context and operates in chunks to handle large datasets. A cleanup action (aadvana_export_large_csv_cleanup) removes temporary files after download.

JavaScript Example

JavaScript
var formData = new FormData();
formData.append('action', 'aadvana_export_large_csv');
formData.append('typeExport', 'requests');
formData.append('_wpnonce', wpNonce);
formData.append('status_filter', 'error');  // Optional filter

fetch(ajaxurl, {
    method: 'POST',
    body: formData,
})
.then(function(r) { return r.json(); })
.then(function(data) {
    if (data.success) {
        console.log('Export file:', data.data.file);
    }
});

9. Hooks & Filters

WordPress Hooks Used for Capture FILTER ACTION

Hook Type Priority Callback Condition
pre_http_request Filter 0 Requests_Log::pre_http_request HTTP logging enabled
http_api_debug Action 10 Requests_Log::capture_request HTTP logging enabled
rest_pre_dispatch Filter 0 Requests_Log::pre_http_request REST logging enabled
rest_request_after_callbacks Filter 10 Requests_Log::capture_rest_request REST logging enabled

Plugin-Specific Hooks HOOK

Hook Type Callback Description
advan_cron_hooks Filter Requests_List::add_cron_job Registers the advan_request_table_clear cron job for automatic table cleanup. Schedule is determined by the advana_rest_requests_clear setting.
admin_post_{PLUGIN_FILTER_ACTION} Action Requests_View::plugin_filter_action Processes plugin filter dropdown form submission on the requests page
manage_{$requests_hook}_columns Filter Requests_List::manage_columns Registers screen columns for the requests list table
load-{$requests_hook} Action Requests_List::process_actions_load Processes bulk actions early (before output) to allow safe redirects

Example: Register a Custom Cron Schedule for Cleanup

PHP
<?php
// Add a custom cleanup interval (every 6 hours)
add_filter( 'cron_schedules', function( $schedules ) {
    $schedules['every_six_hours'] = array(
        'interval' => 21600,
        'display'  => __( 'Every 6 Hours' ),
    );
    return $schedules;
});

// This new schedule will appear in the "Clear requests table every" dropdown
// on the Settings page (Request Options tab).

10. Settings Reference

Settings are rendered using the plugin’s Settings::build_option() builder. The request settings are on the Request Options tab within the main settings page.

PHP
<?php
// Check if requests module is enabled
$enabled = Settings::get_option( 'requests_module_enabled' );

// Check if logging is active
$logging = Settings::get_option( 'advana_requests_enable' );

// Check individual monitoring toggles
$http_disabled = Settings::get_option( 'advana_http_requests_disable' );
$rest_disabled = Settings::get_option( 'advana_rest_requests_disable' );

// Get cleanup schedule
$schedule = Settings::get_option( 'advana_rest_requests_clear' );

Settings Builder Usage

PHP
<?php
// How settings are defined in request-list.php
Settings::build_option(
    array(
        'title' => esc_html__( 'Request Options', '0-day-analytics' ),
        'id'    => 'options-settings-tab',
        'type'  => 'tab-title',
    )
);

Settings::build_option(
    array(
        'name'    => esc_html__( 'Enable requests module', '0-day-analytics' ),
        'id'      => 'requests_module_enabled',
        'type'    => 'checkbox',
        'hint'    => esc_html__( 'Controls the entire requests module.', '0-day-analytics' ),
        'toggle'  => '#advana_requests_settings-item',
        'default' => Settings::get_option( 'requests_module_enabled' ),
    )
);

// The toggle attribute creates a show/hide dependency on the target element.
// When the checkbox is unchecked, #advana_requests_settings-item is hidden.

Settings Dependency Chain


requests_module_enabled (master toggle)
  └── advana_requests_enable (logging toggle)
        ├── advana_http_requests_disable (HTTP sub-toggle)
        └── advana_rest_requests_disable (REST sub-toggle)
advana_rest_requests_clear (cleanup schedule — independent)

11. List Table Columns & Sorting

Columns

Key Header Sortable Description
cb No Bulk selection checkbox
date_added Date Yes ↑ (default DESC) Timestamp when the request was recorded
type Type Yes Request context (admin, ajax, cron, rest_api, etc.)
plugin Plugin Name Yes Originating plugin/theme identified from stack trace
request_status Status Yes Outcome: success, error, or timeout
url URL Yes Target URL (HTTP) or route (REST)
page_url Page Yes WordPress page that initiated the request
domain Domain Yes Target domain extracted from the URL
user_id User Yes WordPress user ID (0 = anonymous/system)
runtime Runtime Yes Request duration in seconds (DECIMAL(10,3))

Filter Parameters (GET)

Parameter Type Description
s string Full-text search across all columns
plugin string Filter by plugin slug (-1 = empty plugin)
status_filter string Filter by status: success, error, timeout
type_filter string Filter by context type (whitelist validated)
domain_filter string Filter by domain (LIKE match)
date_from date Start date (yyyy-mm-dd format validated)
date_to date End date (yyyy-mm-dd format validated)
runtime_min float Minimum runtime in seconds
runtime_max float Maximum runtime in seconds
orderby string Column to sort by (default: id)
order string Sort direction: ASC or DESC (default: DESC)

12. Bulk & Row Actions

Row Actions (per request entry)

Action Method Description
Delete Standard form POST Permanently removes the single request log entry from the database
Details JavaScript modal Opens the request details modal with full request/response data and stack trace

Bulk Actions

Action Description
Delete Records Delete all selected request log entries

Processing Flow

  1. Bulk actions are detected in handle_table_actions()
  2. Called from process_actions_load() on the load-{page_slug} hook (before output)
  3. Nonce verification: auto-generated bulk-{plural} nonce by WP_List_Table
  4. Capability check: manage_options required
  5. After processing, a safe redirect is performed to clean up the URL

13. Analytics Dashboard

The analytics dashboard is rendered by Requests_View::render_analytics_dashboard() using data from Requests_View::get_analytics_data().

Data Queries

Metric SQL Query
Total Requests SELECT COUNT(*) FROM {table}
Requests by Status SELECT request_status, COUNT(*) FROM {table} GROUP BY request_status
Requests by Type SELECT type, COUNT(*) FROM {table} GROUP BY type
Average Runtime SELECT AVG(runtime) FROM {table} WHERE runtime > 0
Last 24 Hours SELECT COUNT(*) FROM {table} WHERE date_added >= {24h_ago}
Last 7 Days SELECT COUNT(*) FROM {table} WHERE date_added >= {7d_ago}
Top 10 Domains SELECT domain, COUNT(*) FROM {table} GROUP BY domain ORDER BY count DESC LIMIT 10
30-Day Trends SELECT DATE(FROM_UNIXTIME(date_added)), COUNT(*), AVG(runtime) GROUP BY date ORDER BY date DESC LIMIT 30

Dashboard Components

  • Summary cards — Total, Last 24h, Last 7d, Avg Runtime, Error Rate
  • Status breakdown — Clickable counts per status (filters the list on click)
  • Type breakdown — Clickable counts per context type (filters the list on click)
  • Top 10 Domains — Most contacted domains (clickable to filter)
  • Performance Trends — Daily table with request count and average runtime for the last 30 days

14. Security & Data Sanitization

Sensitive Data Redaction

The sanitize_request_args() method automatically redacts values for the following keys (case-insensitive):

PHP
<?php
$redact_keys = array(
    'authorization', 'proxy-authorization',
    'cookie', 'set-cookie',
    'x-api-key', 'x-auth-token',
    'api_key', 'apikey',
    'password', 'pass', 'secret', 'client-secret',
    'token', 'access_token', 'refresh_token',
    'signature', '_wpnonce', 'nonce', 'code',
);

Additionally, a heuristic pattern matcher (key_matches_sensitive_pattern()) catches keys containing common sensitive substrings like auth, bearer, credential, etc.

Data Size Limits

Data Type Limit Action
Request argument string values 2,048 bytes Truncated with …[truncated] suffix
Response body preview 512 bytes Truncated with …[truncated] suffix
Full response JSON 4,096 bytes Truncated with …[truncated] suffix

URL Sanitization

Page URLs are sanitised via sanitize_url() before storage. Sensitive query parameters (tokens, keys, passwords) are stripped from the URL string.

Database Security

  • All queries use $wpdb->prepare() with parameterised placeholders
  • All filter inputs are validated against whitelists (status, type) or sanitised with sanitize_text_field()
  • Date range values are validated with regex: /^\d{4}-\d{2}-\d{2}$/
  • Runtime values are validated as numeric before inclusion in queries
  • Table names are validated with preg_match( '/^[a-zA-Z0-9_]+$/' ) in create_table()

Access Control

  • Admin pages require manage_options capability
  • REST API endpoints require manage_options capability
  • Bulk actions verify nonces and capabilities before processing
  • Plugin filter form submissions verify nonces via check_admin_referer()

15. Code Examples

Example 1: Check if Request Logging is Active

PHP
<?php
use ADVAN\Helpers\Settings;

$module_on  = Settings::get_option( 'requests_module_enabled' );
$logging_on = Settings::get_option( 'advana_requests_enable' );
$http_off   = Settings::get_option( 'advana_http_requests_disable' );
$rest_off   = Settings::get_option( 'advana_rest_requests_disable' );

if ( $module_on && $logging_on ) {
    if ( ! $http_off ) {
        // HTTP request logging is active
    }
    if ( ! $rest_off ) {
        // REST request logging is active
    }
}

Example 2: Toggle Monitoring via REST API (JavaScript)

JavaScript
// Disable HTTP monitoring
wp.apiFetch({
    path: '/0-day/v1/requests/http/disable/',
}).then(function() {
    console.log('HTTP monitoring disabled');
});

// Enable REST monitoring
wp.apiFetch({
    path: '/0-day/v1/requests/rest/enable/',
}).then(function() {
    console.log('REST monitoring enabled');
});

Example 3: Query Requests from the Database

PHP
<?php
use ADVAN\Entities\Requests_Log_Entity;

// Get the table name
$table = Requests_Log_Entity::get_table_name();

// Count error requests in the last 24 hours
global $wpdb;
$error_count = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT COUNT(*) FROM {$table} WHERE request_status = %s AND date_added >= %d",
        'error',
        strtotime( '-24 hours' )
    )
);

// Get top 5 slowest requests
$slowest = $wpdb->get_results(
    "SELECT url, runtime, plugin, request_status 
     FROM {$table} 
     ORDER BY runtime DESC 
     LIMIT 5",
    ARRAY_A
);

Example 4: Truncate the Requests Table Programmatically

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

Common_Table::truncate_table( null, Requests_Log_Entity::get_table_name() );

Example 5: Add a Custom Cleanup Schedule

PHP
<?php
// Register a custom schedule
add_filter( 'cron_schedules', function( $schedules ) {
    $schedules['every_six_hours'] = array(
        'interval' => 21600,
        'display'  => __( 'Every 6 Hours' ),
    );
    return $schedules;
});

// The new schedule will automatically appear in the
// "Clear requests table every" dropdown on the settings page.

Example 6: Truncate Table via REST API (JavaScript)

JavaScript
wp.apiFetch({
    path: '/0-day/v1/truncate_table/wp_advan_requests_log/',
    method: 'DELETE',
    cache: 'no-cache',
}).then(function(response) {
    if (response.success) {
        console.log('Requests table truncated');
        location.reload();
    }
}).catch(function(err) {
    console.error('Truncate failed:', err.message);
});

Example 7: Get Request Details via REST API

JavaScript
// Fetch a single request record by ID
wp.apiFetch({
    path: '/0-day/v1/get_table_record/wp_advan_requests_log/42/',
}).then(function(record) {
    console.log('Request URL:', record.url);
    console.log('Runtime:', record.runtime, 'seconds');
    console.log('Status:', record.request_status);
});
Need User Guide documentation?
See Requests Module User Guide for more details about configuration, practical usage and information.
← Requests Module — User Guide 0 Day Analytics – Snippets Module Developer Documentation →
Share this page
Back to top