One of the fundamental rules in web development is to never trust user entered data, failure to do so makes website vulnerable to cross site scripting (XSS) attacks (among others), this is the most common attack i can think of as it requires only a bit of web development knowledge and a web browser.
It is even easier to protect against this attack and yet i see a lot of theme and plugin developers ignoring this very important aspect of web development.
What is user input?
Lets start with what is user input. While this might not be 100% accurate you can think of it as any kind of data that is submitted via some form on your website, it can be comment, post content, or even a password.
Ok, before you start disabling comment sections on your sites, note that by default WordPress handles the user input very well and there is nothing to worry about, this guide is useful only when developing your own custom plugin/theme.
I’ve got user input, now what?
WordPress has a couple of functions for handling user input which one you will be using depends on place where you want to display content, the escaping functions are:
esc_attr - use this to escape HTML tag attributes
esc_html - use this to escape plain text (that is text without HTML markup) content
esc_js - use this to escape JS event attributes is HTML tags for example: onclick, onmouseover and so on.
esc_textarea - use this to escape text entered inside <textarea> tag.
esc_sql - use this to prepare user input data to be saved in DB
esc_url - similar to esc_js except it is used in attributes that require URL for example href or src
The description might be fuzzy, it’s best to look at the example, we will assume that the data was received from $_POST form.
<?php $title = $_POST[‘title’]; $url = $_POST[‘url’]; ?> <a href=”<?php echo esc_url($url) ?>” title=”<?php echo esc_attr($title) ?>”><?php echo esc_html($title) ?></a>
The short example above showcases how to use three functions that you will most likely use most often esc_html, esc_attr and esc_url.
You will probably also want to insert or update some data in DB, then esc_sql function will come in handy, using it is pretty simple, look at the example from from WordPress Codex.
<?php $name = esc_sql( $name ); $status = esc_sql( $status ); $wpdb->get_var( "SELECT something FROM table WHERE foo = '$name' and status = '$status'" ); ?>
Like I wrote at the beginning making sure that the data sent by user is safe is pretty simple, the key is to know that you need to add them and to actually apply those functions.