1.14.3: Escaping Rendered Data

Escaping rendered data

All (even seemingly trusted) outputs should be escaped on the frontend. This includes Store Configuration, product details, and of course, customer/order information.

Go to /teaching/escape for a practical example on these escapes.

\Magento\Framework\Escaper is exposed in every template with the $escaper variable (see the type name="Magento\Framework\View\TemplateEngine\Php reference in app/etc/di.xml). Thus, you have this available anywhere necessary.

escapeHtml($data, $allowedTags)

By NOT passing in $allowedTags, Magento runs the htmlspecialchars method. This is very performant. But if you do need to allow some tags, Magento still prevents several from being allowed: script, img, embed, iframe, video, source, object, audio. For allowed tags, Magento filters attribute values, except for: id, class, href, title, style (the original value is allowed for these attributes).

Use cases:

  • This is to be used anywhere values are rendered into raw HTML.

escapeHtmlAttr($string, $escapeSingleQuote)

This is used whenever you are writing a value into an HTML attribute (pretty self-explanatory).
Use cases:

  • Writing a single value or JSON to an attribute.

escapeUrl($string)

This prevents javascript: and other identifiers from being added to a URL. htmlspecialchars are run on this twice. The second time this happens is when escapeHtml is also called on the input.

Use cases:

  • Anytime you render a URL.

encodeUrlParam($string)

This escapes URL parameters. Magento currently uses this to filter incoming query parameters in a couple of locations.

Example: \Magento\AdobeStockClient\Model\SearchParametersProvider\SimpleFilters::apply

escapeJs($string)

This evaluates all characters that are not in this list: a-z, 0-9, ",", ., _. It ensures all characters are UTF-8 compatible. Then it is converted to a unicode reference.

escapeCss($string)

This ensures that CSS values are safe, specifically converting UTF-32 characters to UTF-8. See here: \Laminas\Escaper\Escaper::cssMatcher.

Note that there are a few deprecated methods that we are not discussing here.

Complete and Continue