How to Sanitize in WordPress

Sanitize

In the world of web development, particularly WordPress, sanitizing input is synonymous with keeping your digital house clean and organized. Sanitizing input implies cleaning user-provided data to ensure its safety before using it in your website or database. This practice is critical for preventing security vulnerabilities like as SQL injections and cross-site scripting (XSS) attacks. Let’s look at how to correctly sanitize input in WordPress.

The Importance of Sanitization

Input sanitization means treating every user input as untrustworthy and potentially destructive. Sanitizing inputs ensures that any data utilized on your website or saved in your database is safe and free of dangerous code.

Sanitization functions

There are many functions in WordPress that will help you sanitize your data. Below is the list.

  1. sanitize_email()
  2. sanitize_text_field()
  3. sanitize_textarea_field()
  4. sanitize_user()
  5. sanitize_url()
  6. sanitize_file_name()
  7. sanitize_hex_color()
  8. sanitize_hex_color_no_hash()
  9. sanitize_html_class()
  10. sanitize_key()
  11. sanitize_mime_type()
  12. sanitize_title()
  13. sanitize_title_with_dashes()
  14. sanitize_meta()
  15. sanitize_option()
  16. sanitize_sql_orderby()
  17. wp_kses()
  18. wp_kses_post()

Sanitizing Email

sanitize_email(): – it is use to Sanitize email addresses.

This function ensures that email address is properly formatted and clean.

Example code:

 <?php 
echo sanitize_email("  webdav contact@webdav.in  "); 
//Output  "webdavcontact@webdav.in"

It removed whitespace characters from email because Email does not allow.

Sanitizing Text Inputs

sanitize_text_field():-it is use to Sanitizes a text input.

Checks for incorrect UTF-8.
Converts single characters into entities.
Removes all html tags.
Eliminates excess spaces, tabs, and line breaks
Removes percent-encoded characters.

 <?php

echo sanitize_text_field("<h2>header<</h2>"); 
//Output "header&lt;" 

Sanitizing Textarea Inputs

sanitize_textarea_field():– it is similar to sanitize_text_field() but it retains line breaks which make it appropriate for text areas.

<?php 
echo sanitize_textarea_field('<h2>Lorem Ipsum is simply dummy text. </h2>');
//Output "Lorem Ipsum is simply dummy text."
 

Sanitize UserName

sanitize_user():– Sanitizes a username by removing any potentially dangerous characters.

Removes tags, percent-encoded characters, and HTML entities. If strict is enabled, only alphanumeric, _, space,., -, and @ characters are kept. After sanitizing, it passes the username, raw username (the username in the argument), and $strict value as parameters to the’sanitize_user’ filter.

Example code:

<?php 
echo sanitize_user('     webdav@123     '); 
	//Output "webdav@123"

Sanitize URL

sanitize_url(): – Sanitizes a URL for database or redirect purposes.

Example code:

<?php
echo  sanitize_url( "example.com/");
	//Output "http://example.com/"

Sanitize File

sanitize_file_name() :- it sanitize file name.

This function remove characters from a filename that can cause issues while referencing the file in the command line. This function is used by WordPress Media Uploader to sanitize media file names.

Example code:

 <?php
echo sanitize_file_name("_user photo--1_.jpg"); 
//Output "user-photo--1_.jpg" 

Sanitize Color Code With Hash

sanitize_hex_color():- it sanitize color code.

it return six digit color code if it is valid hex code otherwise return null

<?php 
//when valid hex code
echo sanitize_hex_color("#000000"); 
//output #000000
//when hex code invalid
echo sanitize_hex_color("0000"); 
//output null

Sanitize Color Code With No Hash

sanitize_hex_color_no_hash(): – it sanitize color code without hash.

it return six digit color code without hash if it is valid hex code otherwise return null.

Example code:-1

<?php 
//when valid hex code
echo sanitize_hex_color("#ffffff"); 
//output ffffff

Example code:-2

//when hex code invalid
echo sanitize_hex_color("ffff"); 
//output null

Sanitizes an HTML classname

sanitize_html_class():– it Sanitize HTML class name.

it remove any spaces and special characters and change it to a valid class name.

Example code:

<?php
echo sanitize_html_class('my!@#$%^&*()class');
//output  myclass

Handle Invalid Class Names with a Fallback

Example code:


<?php 
$class_name = '#@'; // Class names cannot start with a special characters
echo  sanitize_html_class($class_name, 'default-class');
//output  default-class

Sanitize Key

sanitize_key():– it Sanitizes a string key.

Transients, Metadata, and Options Only lowercase alphanumeric characters, underscores, and dashes are permitted in keys. The keys are sanitized by using this function.

Example code:

<?php
echo sanitize_key("Testexample1-_/[]{}");
 //Output testexample1-_

Sanitize Mime Type

sanitize_mime_type():- it Sanitize Mime Type.

Example code:

<?php
echo $mimetype = sanitize_mime_type('mime_example1-_/[]{}.pdf');
//output mimeexample1-/.pdf

Sanitizing Title

sanitize_title():– it convert title string into slug.

it Sanitizes a string to produce a slug that can be used in URLs or HTML properties.

it default transforms accent characters to ASCII characters and restricts the output to alphanumeric characters, underscore (_), and dash (-).

Example code:

<?php 
echo sanitize_title("Sanítize Data in WordPress"); 
//Output "sanitize-data-in-wordpress"

Sanitize Title with Dashes

sanitize_title_with_dashes(): – it Sanitizes a title by replacing whitespace and a few other characters with dashes.

it limits the output to alphanumeric characters, underscores (_), and dashes. Whitespace becomes a dash.

Example code:

<?php 
echo sanitize_title_with_dashes("Website user Data in WordPress"); 
	//Output "website-user-data-in-wordpress"

Sanitize Meta

sanitize_meta():– it sanitize meta.

This function applies filters that can be connected to carry out specified sanitization operations for the given kind and key of metadata. doesn’t clean anything by itself. To function, custom filters need to be hooked in.

The syntax “sanitize_{$meta_type}_meta_{$meta_key}” refers to the filter hook tag.

The WordPress methods add_metadata() and update_metadata() call this function.

Sanitize Option

Sanitize different option values according to the type of option.

This is essentially a switch statement that, depending on the $option, will pass $value through several functions.

Sanitize SQL ‘order by’ clause

sanitize_sql_orderby():– it Sanitizes SQL ‘order by’ clause.

it verifies whether a string fits within a SQL “order by” clause.

it allows for the input of one or more columns in either ascending or descending order. For example, “column 1,” “column 1,” “column 2,” “column 1 ASC, column 2 DESC,” and so on.

Sanitizing HTML Content

wp_kses():– it filters text content and removes any HTML that is not authorized.

If you need to allow some HTML tags (for example, in a rich text editor), use wp_kses_post() for post content or wp_kses() for more specific circumstances where you define the allowable tags and attributes.

Example code:

<?php
//authorized html
$arr = array( 'br' => array(), 'p' => array(), 'strong' => array() );	


//text in which <a> tag will remove
$str = 'I am <strong>stronger</strong> and cooler every single day <a href="#" rel="nofollow ugc">Click Here</a>';

echo  wp_kses( $str, $arr );
////Output I am stronger and cooler every single day Click Here

Sanitizing Post HTML Content

wp_kses_post():– Sanitizes content for post content that contains authorized HTML tags.

Post content refers to the page contents of the ‘post’ type, not the $_POST data from form submissions.

This method expects unslashed data.

Conclusion

We saw what sanitizing is and why it is critical for every developer to understand the functions connected with it. The Data Validation Codex page on WordPress.org contains additional reading material on the issue. It’s always a good idea to include these features when creating a WordPress theme or plugin. Unfortunately, many plugins are poorly constructed and do not escape the output. As a result, they make the website vulnerable to potential XSS attacks. Please feel free to leave any comments or helpful tips in the space below.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top