Usage of esc_url, esc_html, esc_attr ... functions

Stickers picture Stickers · Jan 19, 2015 · Viewed 9k times · Source

When are definitely needed or for a good practice to use escaping functions?

Such as using esc_url(); with:

get_template_directory_uri();
get_permalink();
get_author_posts_url();
get_edit_post_link();
wp_get_attachment_url();

And esc_html(); with:

get_the_title();
get_the_author();
get_the_date();
get_search_query();

Also I think esc_html(); and esc_attr(); are very similar, aren't they? What are the differences?

Answer

Stickers picture Stickers · Feb 12, 2015

Part 1

According to the documentation - Validating, Sanitizing, and Escaping by WP VIP team.

Guiding Principles

  1. Never trust user input.
  2. Escape as late as possible.
  3. Escape everything from untrusted sources (like databases and users), third-parties (like Twitter), etc.
  4. Never assume anything.
  5. Never trust user input.
  6. Sanitation is okay, but validation/rejection is better.
  7. Never trust user input.

“Escaping isn’t only about protecting from bad guys. It’s just making our software durable. Against random bad input, against malicious input, or against bad weather.” –nb

Part 2

According to the article - Introduction to WordPress Front End Security: Escaping the Things by Andy Adams from CSS-Tricks.

Function: esc_html

Used for: Output that should have absolutely no HTML in the output.

What it does: Converts HTML special characters (such as <, >, &) into their "escaped" entity (&lt;, &gt;, &amp;).

Function: esc_attr

Used for: Output being used in the context of an HTML attribute (think "title", "data-" fields, "alt" text).

What it does: The exact same thing as esc_html. The only difference is that different WordPress filters are applied to each function.