Untrusted data comes from many sources (users, third party sites, even your own database!) and all of it needs to be checked before it’s used.
Remember: Even admins are users, and users will enter incorrect data, either on purpose or accidentally. It’s your job to protect them from themselves.
Sanitizing input is the process of securing/cleaning/filtering input data. Validation is preferred over sanitization because validation is more specific. But when “more specific” isn’t possible, sanitization is the next best thing.
Let’s say we have an input field named
<input id="title" type="text" name="title">
We can’t use Validation here because the text field is too general: it can be anything at all. So we sanitize the input data with the
$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
There are many functions that will help you sanitize your data.