Skip to content

Instantly share code, notes, and snippets.

@windyjonas
Last active September 21, 2020 16:10
Show Gist options
  • Save windyjonas/5395390 to your computer and use it in GitHub Desktop.
Save windyjonas/5395390 to your computer and use it in GitHub Desktop.
Most of the escaping functions in WordPress, with a short explanation and example.

WordPress escaping functions

By: Jonas Nordström, @windyjonas
Date: 2013-04-16

esc_attr( $text );
Encodes the <, >, &, " and ' (less than, greater than, ampersand, double quote and single quote) characters. Will never double encode entities.
Example:

<div class="<?php echo esc_attr( $my_class ); ?>"></div>

esc_attr__( $text, $domain );
Retrieves the translation of $text and escapes it for safe use in an attribute. If there is no translation, or the domain isn't loaded the original text is returned.
Example:

<i title="<?php echo esc_attr__( $my_title, 'domain' ); ?>"></i>

esc_attr_e( $text, $domain );
Displays translated text that has been escaped for safe use in an attribute. Encodes < > & " ' (less than, greater than, ampersand, double quote, single quote). Will never double encode entities.
Example:

<i title="<?php esc_attr_e( $my_title, 'domain' ); ?>"></i>

esc_html( $text );
Escaping for HTML blocks.
Example:

<label for="nav-menu"><?php echo esc_html( 'Select Menu:' ); ?></label>

esc_html__( $text, $domain );
Example:

<label for="nav-menu"><?php echo esc_html__( 'Select Menu:', 'domain' ); ?></label>

esc_html_e( $text, $domain );
Displays translated text that has been escaped for safe use in HTML output.
Example:

<label for="nav-menu"><?php esc_html_e( 'Select Menu:', 'domain' ); ?></label>

esc_js( $text );
Escape single quotes, htmlspecialchar " < > &, and fix line endings. Escapes text strings for echoing in JS. It is intended to be used for inline JS (in a tag attribute, for example onclick="…"). Note that the strings have to be in single quotes. The filter ‘js_escape’ is also applied here.
Example:

<input type="text" value="<?php echo esc_attr( $instance['input_text'] ); ?>" id="subbox"   
onfocus="if ( this.value ==  '<?php echo esc_js( $instance['input_text'] ); ?>') { this.value = ''; }"   
onblur="if ( this.value == '' ) { this.value = '<?php echo esc_js( $instance['input_text'] ); ?>'; }"   
name="email" />

esc_textarea( $text );
Encodes text for use inside a <textarea> element.
Example:

<textarea id="my_id" cols="50" rows="5" name="my_name"><?php echo esc\_textarea( $my_textarea ); ?></textarea>

esc_url( $url, $protocols = null, $_context = 'display' );
Always use esc_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). Rejects URLs that do not have one of the provided whitelisted protocols (defaulting to http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed, and telnet), eliminates invalid characters, and removes dangerous characters. This function encodes characters as HTML entities: use it when generating an (X)HTML or XML document. Encodes ampersands (&) and single quotes (') as numeric entity references (&#038, &#039).
Replaces the deprecated clean_url().
Example:

printf( '<a href="%s" class="link">%s</a>', esc_url( get_permalink() ), esc_html( get_the_title() ) );

esc_url_raw( $url, $protocols=null );
The esc_url_raw() function is similar to esc_url() (and actually uses it), but unlike esc_url() it does not replace entities for display. The resulting URL is safe to use in database queries, redirects and HTTP requests. esc_url() encodes HTML entities, while esc_url_raw() does not esc_url() is intended for output, while esc_url_raw() is intended for database storage
Example:

$response = wp_remote_get( esc_url_raw( $url ) ); // no need to espace entities

urlencode ( $str );
This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
Example:

echo '<a href="mycgi?foo=', urlencode($userinput), '">';

urlencode_deep( $value );
Navigates through an array and encodes the values to be used in a URL.
Uses a callback to pass the value of the array back to the function as a string.

Integers

intval( $int ) or (int) $int
If it's supposed to be an integer, cast it as one.

absint( $int )
Ensures that the result is nonnegative.

Sanitize input

sanitize_text_field( $str );
Checks for invalid UTF-8, Convert single < characters to entity, strip all tags, remove line breaks, tabs and extra white space, strip octets.

sanitize_email( $email );
Strips out all characters that are not allowable in an email.

sanitize_file_name( $name );
Sanitizes a filename replacing whitespace with dashes Removes special characters that are illegal in filenames on certain operating systems and special characters requiring special escaping to manipulate at the command line. Replaces spaces and consecutive dashes with a single dash. Trim period, dash and underscore from beginning and end of filename.

sanitize_html_class( $class, $fallback );
Sanitizes a html classname to ensure it only contains valid characters. Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty string, then the function will return the alternative value supplied. After sanitize_html_class() has done its work, it passes the sanitized class name through the sanitize_html_class filter.
Example:

<?php
// If you want to explicitly style a post, you can use the sanitized version of the post title as a class
$post_class = sanitize_html_class( $post->post_title );
echo '<div class="' . esc_attr( $post_class ) . '">'; ?>

sanitize_key( $key );
Sanitize a string key. Keys are used as internal identifiers.
Lowercase alphanumeric characters, dashes and underscores are allowed. Uppercase characters will be converted to lowercase. After sanitize_key() has done its work, it passes the sanitized key through the sanitize_key filter.

sanitize_mime_type( $mime_type );

sanitize_option( $option, $value );
Sanitizes various option values based on the nature of the option.
This is basically a switch statement which will pass $value through a number of functions depending on the $option. After the value has been handled by these functions, it will be passed through a sanitize_option_$option filter.

sanitize_sql_orderby( $orderby );
Ensures a string is a valid SQL order by clause.
Accepts one or more columns, with or without ASC/DESC, and also accepts RAND().

sanitize_title( $title, $fallback_title, $context );
Sanitizes title or use fallback title.
Specifically, HTML and PHP tags are stripped, and (in a 'save' context) accents are removed (accented characters are replaced with non-accented equivalents). Further filtering can be added via the plugin API by hooking the sanitize_title filter. If $title is empty and $fallback_title is set, the latter will be used.
Example:

<?php
$new_url = sanitize_title('This Long Title is what My Post or Page might be');
  echo $new_url;
?>

It should return a formatted value, the output would be this:
this-long-title-is-what-my-post-or-page-might-be

sanitize_title_for_query( $title );
Sanitizes a title with the 'query' context. Used for querying the database for a value from URL.
Shorthand for sanitize_title($title, "", "query") (See sanitize_title()).

sanitize_title_with_dashes( $title, $unused, $context = 'display' )
Sanitizes title, replacing whitespace with dashes. Limits the output to alphanumeric characters, underscore (_) and dash (-). Whitespace becomes a dash
Example:

sanitize_user( $username, $strict );
Sanitize username stripping out unsafe characters. If $strict is true, only alphanumeric characters plus these: _, space, ., -, *, and @ are returned.
Removes tags, octets, entities, and if strict is enabled, will remove all non-ASCII characters. After sanitizing, it passes the username, raw username (the username in the parameter), and the strict parameter as parameters for the sanitize_user filter.

Filesystem

validate_file( (string) $filename, (array) $allowed_files = "" )
Used to prevent directory traversal attacks, or to test a filename against a whitelist. Returns 0 if $filename represents a valid relative path. After validating, you must treat $filename as a relative path (i.e. you must prepend it with an absolute path), since something like /etc/hosts will validate with this function. Returns an integer greater than zero if the given path contains .., ./, or :, or is not in the $allowed_files whitelist. Be careful making boolean interpretations of the result, since false (0) indicates the filename has passed validation, whereas true (> 0) indicates failure.

is_email( $email_address )
returns boolean false if invalid, or $email_address if valid

More info at The Codex page about Data Validation

@luiseduardobraschi
Copy link

urlencode is actually a native PHP function.

@castroalves
Copy link

Thanks! Useful and very well explained!

@pagelab
Copy link

pagelab commented Jul 20, 2018

sanitize_hex_color()is also available (WP 4.6+). See https://developer.wordpress.org/reference/functions/sanitize_hex_color/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment