Sanitize and validate user input in WordPress the right way

Sanitize and validate user input in WordPress the right way

Everything that comes into a WordPress site from outside (form fields, URL parameters, REST requests, shortcode attributes) is a possible attack. SQL injection and cross-site scripting almost always start with input that reaches a query, an echo or a file path unprocessed. WordPress has a function for nearly every case; the hard part is using them consistently.

Problem: Which sanitizing and escaping function should be used for each kind of data to prevent XSS and injections?

Solution: The golden rule: validate and sanitize on input, escape on output. Sanitizing cleans the data before it is stored; escaping makes it safe for the specific place where it is printed.

Sanitize on input

WordPress adds slashes to $_POST, $_GET and $_COOKIE, so remove them with wp_unslash() before sanitizing:

<?php
$name    = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );       // one line, no tags
$bio     = sanitize_textarea_field( wp_unslash( $_POST['bio'] ?? '' ) );    // several lines, no tags
$email   = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );           // only valid email characters
$website = esc_url_raw( wp_unslash( $_POST['website'] ?? '' ) );            // a URL for the database
$count   = absint( $_POST['count'] ?? 0 );                                  // a non-negative integer
$slug    = sanitize_title( wp_unslash( $_POST['slug'] ?? '' ) );            // a URL-safe slug
$key     = sanitize_key( wp_unslash( $_POST['key'] ?? '' ) );               // lowercase letters, digits, - and _
$content = wp_kses_post( wp_unslash( $_POST['content'] ?? '' ) );           // only the HTML allowed in posts

Validate

Sanitizing makes a value harmless, but not correct. Check what the field must contain and reject the rest:

<?php
if ( ! is_email( $email ) ) {
    $errors[] = __( 'Please enter a valid email address.', 'theme-name' );
}

$allowed_plans = array( 'basic', 'pro' );
$plan = sanitize_key( wp_unslash( $_POST['plan'] ?? '' ) );
if ( ! in_array( $plan, $allowed_plans, true ) ) {
    $errors[] = __( 'Unknown plan.', 'theme-name' );
}

Escape on output

The function depends on where the value is printed:

<?php
echo esc_html( $name );            // inside HTML
echo '<input value="' . esc_attr( $name ) . '">'; // inside an attribute
echo '<a href="' . esc_url( $website ) . '">';    // in href / src
echo '<textarea>' . esc_textarea( $bio ) . '</textarea>';
echo wp_kses_post( $content );     // rich HTML
echo '<script>var data = ' . wp_json_encode( $data ) . ';</script>'; // data for JavaScript

Escape as late as possible, right in the echo, even if the value was sanitized when it was saved: the database or the option may have been changed by other code.

Database queries

Never put variables into SQL directly, use $wpdb->prepare():

<?php
global $wpdb;
$results = $wpdb->get_results( $wpdb->prepare(
    "SELECT ID FROM {$wpdb->posts} WHERE post_author = %d AND post_status = %s LIMIT %d",
    $user_id,
    'publish',
    10
) );

Nonces for forms

A nonce proves that the form was sent from your site by the same user, which protects against CSRF:

<?php
// In the form
wp_nonce_field( 'helloadmin_save_settings', 'helloadmin_nonce' );

// In the handler
if ( ! isset( $_POST['helloadmin_nonce'] )
    || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['helloadmin_nonce'] ) ), 'helloadmin_save_settings' ) ) {
    wp_die( esc_html__( 'Security check failed', 'theme-name' ) );
}

if ( ! current_user_can( 'manage_options' ) ) {
    wp_die( esc_html__( 'You are not allowed to do this.', 'theme-name' ) );
}

A nonce does not check rights: always add current_user_can().

NOTE: Headers like X-Forwarded-For are also user input: anyone can send them. If you use the visitor’s IP for limits or logs, take $_SERVER['REMOTE_ADDR'], and read forwarded headers only when the request comes from your own proxy or CDN. The same rules for shortcode attributes are shown in creating a shortcode with attributes.