SponsoredHosinger Special Offer

WP+ WordPress Plugin Development

Build WordPress plugins from scratch: actions and filters, shortcodes, settings pages, custom post types, meta boxes, AJAX, REST endpoints, custom tables, cron and blocks.

Sanitizing, Validating and Escaping

WordPress Plugin Development Lesson 13 of 27 ~3 min read

Overview

Secure plugins follow one rule for data: sanitise and validate everything that comes in — from forms, URLs, cookies and APIs — and escape everything that goes out to the browser, at the moment it is printed.

Three different jobs

StepWhenQuestionExample
ValidateInputIs this acceptable at all?Is the ISBN 10 or 13 digits?
SanitiseInputMake it safe to storeStrip tags from a name
EscapeOutputMake it safe for this exact spot in HTMLesc_attr() inside an attribute

Always unslash first

WordPress adds backslashes to everything in $_POST, $_GET and $_COOKIE for historical reasons. Remove them with wp_unslash() before sanitising, or a name like O'Brien is stored as O\'Brien.

<?php
$title = isset( $_POST['gdc_title'] )
    ? sanitize_text_field( wp_unslash( $_POST['gdc_title'] ) )
    : '';

Sanitising functions

Input isSanitise with
A single line of textsanitize_text_field()
Multi-line textsanitize_textarea_field()
An email addresssanitize_email()
A URL to storeesc_url_raw()
A positive integer / IDabsint()
A key or slugsanitize_key() / sanitize_title()
A hex coloursanitize_hex_color()
A file namesanitize_file_name()
HTML that may contain post-safe tagswp_kses_post()

Validation: reject what is wrong

Sanitising makes data safe; validating makes it correct. An ISBN with letters in it is "safe" after sanitize_text_field() but still wrong:

<?php
function gdc_books_validate_isbn( $raw ) {
    $isbn = preg_replace( '/[^0-9X]/', '', strtoupper( $raw ) );

    if ( ! in_array( strlen( $isbn ), array( 10, 13 ), true ) ) {
        return new WP_Error( 'gdc_books_bad_isbn', __( 'An ISBN must have 10 or 13 digits.', 'gdc-books' ) );
    }

    return $isbn;
}

$isbn = gdc_books_validate_isbn( wp_unslash( $_POST['gdc_isbn'] ?? '' ) );

if ( is_wp_error( $isbn ) ) {
    // Show $isbn->get_error_message() and do not save.
}
Tip: Prefer allow-lists to block-lists. Checking a value is one of array( 'date', 'title' ) is airtight; trying to list every bad value never is.

Escaping on output

Even data you sanitised on the way in must be escaped on the way out — it might have been changed in the database by another plugin, or saved before your validation existed:

<?php $isbn = get_post_meta( $post->ID, '_gdc_books_isbn', true ); ?>

<input type="text" name="gdc_isbn" value="<?php echo esc_attr( $isbn ); ?>">
<a href="<?php echo esc_url( 'https://openlibrary.org/isbn/' . rawurlencode( $isbn ) ); ?>">
    <?php echo esc_html( $isbn ); ?>
</a>

SQL: always prepare

Sanitising text does not make it safe for SQL. Any query that includes a variable must use $wpdb->prepare() (lesson 20):

<?php
global $wpdb;

// Wrong — SQL injection:
// $wpdb->get_results( "SELECT * FROM {$wpdb->posts} WHERE post_title = '$title'" );

// Right:
$rows = $wpdb->get_results(
    $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = %s", $title, 'gdc_book' )
);

Practice

  • Write an ISBN field handler that unslashes, validates with WP_Error and sanitises.
  • Save a title containing <script>alert(1)</script> and confirm it is stored without tags and displayed as text.
  • Find every $_POST and $_GET in your plugin and check each passes through wp_unslash() and a sanitiser.
Create a free account to save which lessons you've finished. Save my progress