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.
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).
This helper function encodes text for use inside a <textarea> element.
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.
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: https://codex.wordpress.org/Function_Reference/sanitize_title
This helper function is used for sanitizing an email address by stripping out any invalid characters.
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: https://codex.wordpress.org/Data_Validation
Always remember to follow basic web security principles: FILTER IN ESCAPE OUT.