Yogesh Chauhan's Blog

Sanitize inputs using built-in WordPress functions

in WordPress on July 20, 2021

When you have a plugin or a theme, you might have a form that requires a data validation. Filtering and cleaning out the user inputs is the first step in securing the user inputs.

Sanitize has a deeper meaning. Sanitize is not restricting user to enter a specific type of inputs but rather cleaning it when user submits some data.

At the end, you do the dirty cleaning rather than forcing users to do the work and enter the perfect input.

That doesn’t work in all cases and it doesn’t mean that you let users enter number instead of texts and do some magic cleaning. That’s not what it is.

It’s a good practice to sanitize or validate user inputs that might be unsafe rather than just adding directly into the database.

WordPress provides many functions using which you can sanitize the user inputs.

Most of those functions start with “sanitize_“.

Let’s go through it one by one.

sanitize_email

sanitize_email removes all the characters that are no supposed to be in an email. For example, spaces.


$sanitized_email = sanitize_email('     [email protected]!     ');
echo $sanitized_email; 
// '[email protected]'


sanitize_file_name

sanitize_file_name is used to replace white spaces with dashes.

It does few more things:

  • It removes special characters from the filenames which are considered illegal but on certain OS only.
  • It removes special characters that requires escaping to write the filenames on the command line.
  • It replaces spaces with dashes.
  • It merges consecutive dashes with a single dash.
  • It removes/trims underscores, dash and periods from the beginning and end of the filename.
  • It is NOT guaranteed that sanitize_file_name function will return a filename that is allowed to be uploaded so you might still need to update the filename after sanitization it.

sanitize_file_name($filename)

sanitize_hex_color

sanitize_hex_color is helpful to sanitize hex colors. It’ll return either 3 or 6 digit hex colors with hash (#). If you pass an empty string, it won’t return anything.


sanitize_hex_color($color)


sanitize_hex_color_no_hash

No brainer. The name says it all.

sanitize_hex_color_no_hash does the same thing as sanitize_hex_color but without the hash.

sanitize_html_class

sanitize_html_class function sanitizes the html class name and remove everything else other than A-Z,a-z,0-9,_,-

This is how you can use it:


sanitize_html_class($class, $fallback)

$fallback will be returned in case of sanitized string results in an empty string.

sanitize_key

sanitize_key is used to sanitize keys that only allows dashes, underscores and alphanumeric characters. Keys are used as internal identifiers.

sanitize_meta

sanitize_meta is used for sanitizing meta values.

The syntax is:


sanitize_meta($meta_key, $meta_value, $object_type, $object_subtype)

First 3 args are required.

This is how you can use it:


sanitize_meta( 'birth-year', $user_input, 'user' );


sanitize_text_field

sanitize_text_field does few things:

  • Converts single < characters to entities
  • Checks for invalid UTF-8,
  • Removes line breaks, tabs, and extra whitespace
  • Strips all tags
  • Strips octets

$string = "<h1>Title</h1>";
echo sanitize_text_field( $string ); 
//Title


sanitize_textarea_field

sanitize_textarea_field does the exact same thing but for multiple strings and keeps new lines (\n) and white spaces.

sanitize_title

sanitize_title converts a string into a slug.

sanitize_title also converts accent characters to ASCII characters. It also limits the output to underscore (_), dash (-) and alphanumeric characters.

the syntax is:


sanitize_title($title, $fallback, $context)

Only the first argument is required. If you pass $fallback then it’ll be returned in case of empty title.

For the $content argument, the default value is ‘save’. It asks for a operation for which the string is sanitized. If you want to save the data into a database, you set it to ‘save’ and the string runs through remove_accents(). If you want to use ot for WHERE query, pass ‘query’ as $context.

This is how you can use sanitize_title:


$new_url = sanitize_title('This is a Title');
echo $new_url;
// this-is-a-title



sanitize_title_for_query

If you don’t want to pass ‘query’ as $context in the sanitize_title function then just use this function. It does the same thing.

sanitize_title_with_dashes

sanitize_title_with_dashes does the thing as per the name. It sanitizes the title and replaces white spaces and few other characters with dashes.

Same syntax as sanitize_title with default $context value as ‘display’. If you change it to ‘save’ then additional entities are converted to hyphens or stripped entirely.

sanitize_user

sanitize_user strips out unsafe characters from username string.

wp_kses

KSES = KSES Strips Evil Scripts

wp_kses filters text content and removes HTML that’s not allowed.

wp_kses_post

wp_kses_post does the same thing as wp_kses but for post content.

few more…

  • sanitize_sql_orderby
  • sanitize_mime_type
  • sanitize_option
  • esc_url_raw

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create a smooth scrolling effect with CSS?CSSIs there a CSS parent selector?CSS@forward modules with a prefix in SCSS (Sass)SCSSSelector Lists and Combinators in SCSS (Sass)SCSSHow to create bouncing balls using HTML canvas and JavaScript?HTMLUPDATE and DELETE Statements in PostgresPostgres