Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of esc_url, esc_html, esc_attr ... functions

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?

like image 220
Stickers Avatar asked Jan 19 '15 17:01

Stickers


1 Answers

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

  • Codex entry for esc_html
  • Codex entry for esc_attr

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.

like image 107
Stickers Avatar answered Oct 09 '22 19:10

Stickers