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
<?php echo get_permalink() . '?order=time' ?>
you should be in the habit of using an escape function because you typed some of the actual URL.
<?php echo esc_url(get_permalink() . '?order=time') ?>
Still, it would be better to use the add_query_string function like this
<?php echo add_query_arg('order', 'time', get_permalink()) ?>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With