Data Validation, Sanitization and Escaping

Don’t ever trust your users. Always validate, sanitize and escape every piece of information that saves into and read out of your database.

So, what exactly validation, sanitization and escaping? Do we really need them?

  • Validation is the ruleset to make sure data received from end user is in correct format that you expect it to be.
  • Sanitization is the process of removing unwanted character or information received from end user before saving it to the database.
  • Escaping is the process of cleaning data that you have in your database before displaying it to the end user.

So, now you know about validation, sanitization and escaping, lets talk about different built-in helper function that WordPress provides for it.

  1. esc_url( $url, (array) $protocols = null )

    This helper function escapes URL by checking if it has appropriate protocol and stripping invalid characters.

  2. esc_html($text)

    This helper function escapes HTML content by encoding some of the special characters. There is similar helper function to escape HTML attributes esc_attr($text).

  3. esc_textarea($text)

    This helper function encodes text for use inside a <textarea> element.

  4. sanitize_text_field($text)

    This helper function is used for sanitizing any string input by user or read from database. It checks for invalid UTF-8 character, converts single < characters to entity, strips all tags, remove line breaks, tabs and extra whitespaces.

  5. sanitize_title($title)

    This helper function is used for sanitizing a title by stripping HTML tags. You can also pass fallback title as a second argument in a function. You can read more on this link:

  6. sanitize_email($email)

    This helper function is used for sanitizing an email address by stripping out any invalid characters.

  7. is_email($email)

    This helper function is used for checking if provided email address is valid one. It returns Boolean value.

  8. wp_kses( (string) $fragment, (array) $allowed_html, (array) $protocols = null )

    This helper function is used to make sure only allowed HTML elements, attributes and values are allowed. It is basically whitelisting HTML tags that you want to use. If you don’t want to pass array of allowed HTML tags, there are helpful function such as wp_kses_post($string) that allows tags which are used in post/pages and wp_kses_data($string) that allows tags which are whitelisted in comments.

You can view other helpful data validation and sanitization function on this link:

Always remember to follow basic web security principles: FILTER IN ESCAPE OUT.