Can someone explain when to use escaping functions?
My goal is to secure my WordPress theme. I used a blank theme by Chris Coyier and added code to make the website I wanted. I noticed other themes used escaping functions but not Coyier’s blank theme so I want to understand where to insert these.
After reading Codex and google results and researching the code of a few themes, I am still unclear on when to use
esc_url()
esc_attr()
esc_html()
I do not see a pattern of when to use these. For example, in one theme, for home_url ( ‘/’ ) — notice that esc_url is used in header.php but not in searchform.php — Why?
header.php
<a href=
// NOTICE ESCAPING FUNCTION BELOW
"<?php echo esc_url( home_url( '/' ) ); ?>"
title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a>
searchform.php
<form role="search" method="get" id="searchform" action=
// NO ESCAPING FUNCTION BELOW
"<?php echo home_url( '/' ); ?>"
>
The escape functions serve to protect against attacks and weird characters. Some of the things the functions do is remove invalid characters, remove dangerous characters, and encode characters as HTML entities.
The problem is that untrusted data comes from not just users, but could come from things saved in your own database.
As a general rule, it is good to use the escape functions when any part of the URL is not generated by WordPress functions. If the entire URL is generated only by WordPress functions then the escape functions are not necessary.
For example, if you wanted to print the URL and add a query string like this
you should be in the habit of using an escape function because you typed some of the actual URL.
Still, it would be better to use the add_query_string function like this
In this second example, you would not need an escape function because the URL is generated entirely by WordPress functions.
In your example in the question, the escape function is not necessary in the header.php file. The person who wrote that code was probably just in the habit of doing it and it is ok to put there even when it is not needed.
A good place to start reading about data validation would be on the WordPress codex: https://codex.wordpress.org/Data_Validation
You need to use the wordpress escape function for any user inserted content, not necesary for wordpress function. But in plugins, template, forms or stuff like this you need to use the escape functions.
You need to use the wordpress escape functions for any user insert content as John says ..
Have a look at the link i provided to know about wordpress escape functions..
http://codeseekah.com/2012/03/13/wordpress-escape-functions/