Validate, Sanitize, and Escape
Three Different Jobs
| Step | Question | Example Function |
|---|---|---|
| Validate | Is this value acceptable? | in_array(), filter_var() |
| Sanitize | How should this value be cleaned? | sanitize_text_field(), absint() |
| Escape | How should this value be printed safely? | esc_html(), esc_attr(), esc_url() |
Do not treat these as interchangeable.
Input Sources Are Untrusted
Treat these as untrusted:
$_GET$_POST$_REQUEST- cookies
- REST request parameters
- AJAX payloads
- imported data
- saved options created by older code
Unslash Input
WordPress adds slashes to request data. Use wp_unslash() before sanitizing superglobal values.
$raw_email = isset($_POST['email']) ? wp_unslash($_POST['email']) : '';
$email = sanitize_email($raw_email);
if (! is_email($email)) {
wp_die(esc_html__('Invalid email address.', 'my-plugin'));
}
Sanitization Functions
| Data Type | Function |
|---|---|
| Plain text | sanitize_text_field() |
| Multiline text | sanitize_textarea_field() |
sanitize_email() | |
| URL for database | esc_url_raw() |
| Key or slug | sanitize_key() |
| File name | sanitize_file_name() |
| Integer | absint() |
Escaping Functions
Escape as late as possible, where output is printed.
<p><?php echo esc_html($message); ?></p>
<input value="<?php echo esc_attr($field_value); ?>">
<a href="<?php echo esc_url($url); ?>">Visit</a>
For trusted post-like HTML, use wp_kses_post().
echo wp_kses_post($description_html);
Validation Example
$allowed_layouts = ['grid', 'list'];
$layout = isset($_GET['layout']) ? sanitize_key(wp_unslash($_GET['layout'])) : 'grid';
if (! in_array($layout, $allowed_layouts, true)) {
$layout = 'grid';
}
Common Pitfalls
- Sanitizing but never validating allowed values
- Escaping before saving to the database, then double-escaping on output
- Using
esc_html()for URLs or attributes - Trusting saved options because they are already in the database
What's Next
Deep WordPress Application
This lesson is most useful when applied to real WordPress code rather than isolated PHP examples. Validate, Sanitize, and Escape affects how a site behaves under plugins, themes, editors, logged-in users, guests, cached pages, REST requests, and production traffic.
Security in WordPress PHP is mostly about strict boundaries: untrusted input enters, normalized data is stored, escaped output leaves.
A practical implementation should answer four questions before code is written:
- Which WordPress request context will run this code?
- Which API or hook owns the behavior?
- Which data is trusted, and which data must be normalized?
- What should happen when the expected data, permission, or dependency is missing?
WordPress API Anchor
For this topic, a common API or integration point is sanitize_text_field(). The exact function may vary by feature, but the design principle is stable: use WordPress APIs before inventing custom plumbing.
A common hook or lifecycle point for this topic is admin_post_. Confirm the hook runs in the request type you care about before attaching expensive or state-changing logic.
Focused Code Pattern
$message = isset($_POST['message'])
? sanitize_text_field(wp_unslash($_POST['message']))
: '';
if ('' === $message) {
wp_die(esc_html__('A message is required.', 'my-plugin'));
}
This pattern should still be adapted to the exact feature. Add capability checks for private data, nonces for browser-submitted state changes, and output escaping when rendering values.
Data Flow Walkthrough
| Stage | What To Decide | WordPress Example |
|---|---|---|
| Source | Where the value comes from | Request data, option, post meta, user meta, REST parameter, remote API |
| Trust | Whether the value can be used directly | Treat external, request, and old saved values as untrusted |
| Normalize | How PHP converts the value into a safe shape | absint(), sanitize_text_field(), sanitize_key(), custom allow-list |
| Authorize | Who can read or change it | current_user_can() with a specific capability |
| Persist | Where the value belongs | Option, post meta, user meta, taxonomy term, custom table |
| Render | How the value leaves PHP | esc_html(), esc_attr(), esc_url(), wp_kses_post() |
Applied Practice
Take one request parameter and document its full path from input, to validation, to storage, to escaped output.
When practicing, do not stop when the happy path works. WordPress code becomes reliable when the failure paths are equally deliberate.
Expanded Decision Guide
| Decision | Prefer This | Avoid This |
|---|---|---|
| Where code lives | A plugin for durable behavior, a theme for presentation | Editing WordPress core or vendor plugin files |
| How data enters | A named request handler with validation | Reading superglobals deep inside templates |
| How data is stored | WordPress APIs with clear keys and types | Unstructured arrays with undocumented meanings |
| How output is printed | Escape at the final output context | Trusting saved data because it came from the database |
| How failures behave | Return early, log safely, show useful messages | Fatal errors, blank pages, or exposed stack details |
| How changes ship | Small reviewed changes with rollback notes | Large untested edits directly on production |
Implementation Checklist
Use this checklist when applying the lesson in a real WordPress codebase.
- Identify whether the code belongs in a plugin, child theme, block, mu-plugin, or deployment script.
- Name functions, classes, options, actions, filters, and CSS hooks with a project-specific prefix.
- Confirm which hook should run the code and whether that hook fires in admin, front end, AJAX, REST, cron, or CLI contexts.
- Validate every value that comes from a request, database option, custom field, remote API, cookie, or file.
- Sanitize before storing data and escape at the exact output boundary.
- Check the narrowest useful capability before reading private data or changing state.
- Add nonces or signed requests for state-changing browser actions.
- Keep database queries narrow by requesting only the fields and post types needed.
- Reset global WordPress state after custom queries, site switching, or temporary filters.
- Add a short manual test note for the main success path and at least one failure path.
Extended Example Pattern
The following pattern is intentionally small. It demonstrates how to keep request handling, normalization, and output separate enough to review.
add_action('admin_post_myplugin_example_action', 'myplugin_handle_example_action');
function myplugin_handle_example_action(): void {
if (! current_user_can('manage_options')) {
wp_die(esc_html__('You are not allowed to do that.', 'my-plugin'));
}
check_admin_referer('myplugin_example_action', 'myplugin_nonce');
$label = isset($_POST['label'])
? sanitize_text_field(wp_unslash($_POST['label']))
: '';
if ('' === $label) {
wp_safe_redirect(add_query_arg('status', 'missing-label', wp_get_referer() ?: admin_url()));
exit;
}
update_option('myplugin_example_label', $label, false);
wp_safe_redirect(add_query_arg('status', 'saved', wp_get_referer() ?: admin_url()));
exit;
}
Troubleshooting Matrix
| Symptom | Likely Cause | First Check |
|---|---|---|
| Callback never runs | Wrong hook name, priority, or load context | Confirm the hook fires in this request type |
| Data saves incorrectly | Missing unslash, sanitization, or type normalization | Log sanitized values in development only |
| Output looks broken | Escaped for the wrong context or escaped too early | Check whether the output is text, HTML, URL, or attribute |
| Permission bug | Role check is too broad or capability is missing an object ID | Use current_user_can() with the specific operation |
| Slow page | Query, HTTP request, or loop work runs on every request | Profile with Query Monitor and add caching or batching |
| Works locally only | PHP version, plugin dependency, rewrite rule, or environment setting differs | Compare environment versions and enabled plugins |
Practice Exercise
- Recreate the smallest practical example from this lesson in a local WordPress site.
- Add one valid input and one invalid input.
- Confirm the invalid input fails safely without changing stored data.
- Confirm the valid input is sanitized before storage.
- Render the stored value in at least two contexts, such as text and attribute output.
- Add a capability check and verify a lower-privilege user cannot perform the action.
- Temporarily enable debug logging and confirm no PHP warnings appear.
- Remove temporary logs before treating the example as complete.
Review Questions
- What WordPress hook or API makes this lesson reliable in the right request context?
- Which values in the example are untrusted at the moment they enter PHP?
- Where should validation happen, and where should output escaping happen?
- What user capability is required for the action, and why is that the narrowest useful choice?
- What is the expected behavior when the required data is missing or malformed?
- What would need to change before this code runs safely on a large production site?
Production Notes
Production WordPress PHP should be easy to audit under pressure. Keep the control flow direct, keep side effects visible, and prefer small functions that name the business rule they enforce. If a future maintainer cannot identify the request source, permission check, data normalization, and output boundary in a few minutes, the code is too implicit.