Securing Input
Topics
Securing input is the process of sanitizing (cleaning, filtering) input data.
You use sanitizing when you don’t know what to expect or you don’t want to be strict with data validation.
Any time you’re accepting potentially unsafe data, it is important to validate or sanitize it.
Sanitizing the Data Sanitizing the Data
The easiest way to sanitize data is with built-in WordPress functions.
The sanitize_*()
series of helper functions are super nice, as they ensure you’re ending up with safe data, and they require minimal effort on your part:
- sanitize_email()
- sanitize_file_name()
- sanitize_hex_color()
- sanitize_hex_color_no_hash()
- sanitize_html_class()
- sanitize_key()
- sanitize_meta()
- sanitize_mime_type()
- sanitize_option()
- sanitize_sql_orderby()
- sanitize_text_field()
- sanitize_title()
- sanitize_title_for_query()
- sanitize_title_with_dashes()
- sanitize_user()
- esc_url_raw()
- wp_filter_post_kses()
- wp_filter_nohtml_kses()
Example Example
Let’s say we have an input field named title.
<input id="title" type="text" name="title">
You can sanitize the input data with the sanitize_text_field() function:
$title = sanitize_text_field($_POST['title']); update_post_meta($post->ID, 'title', $title);
Behind the scenes, sanitize_text_field() does the following:
- Checks for invalid UTF-8
- Converts single less-than characters (<) to entity
- Strips all tags
- Removes line breaks, tabs and extra white space
- Strips octets