All dynamic data must be correctly escaped for the context where it is rendered.
All dynamic data must be escaped with
esc_attr() before rendered in an html attribute.
<p title="<?php echo $text; ?>">My Paragraph.</p>
In the example above, we are echoing the value of the
$text variable in the
title attribute of a paragraph. This is problematic for two reasons:
$textmay contain malicious data resulting in a XSS exploit.
$textmay contain valid data that causes the html to break. A lone double quote would result in invalid markup which may cause the page to render poorly.
<p title="<?php echo esc_attr( $text ); ?>">My Paragraph.</p>
esc_attr() is a great catch all function for escaping dynamic data in html attributes, but it is not the only option. In some situations it may be better to use a function that filters more aggressively. Please see the sections below for recommended functions.
Whenever you are rendering a url to the screen its value must be passed through
esc_url() first. This will ensure that:
- The value is safe to use in HTML attributes.
- Special characters, like ampersands, are replaced with HTML entities.
The following example shows a dynamic value rendered inside an html attribute.
<a href="<?php echo $variable; ?>">
Passing the value of
esc_url() before it is rendered will ensure that it is formated correctly.
<a href="<?php echo esc_url( $variable ); ?>">
<a href="#" onclick="alert( '<?php echo $variable; ?>' );">
Passing the value of the variable through
esc_js() ensures that the value will be in the correct format before it is rendered to the screen.
<a href="#" onclick="alert( '<?php echo esc_js( $variable ); ?>' );">
esc_js() to all values passed to the
Data Validation in the WordPress Codex.