Chris@0: # Escaping HTML Attributes
Chris@0:
Chris@0: Escaping data in **HTML Attribute** contexts is most often done incorrectly, if
Chris@0: not overlooked completely by developers. Regular [HTML
Chris@0: escaping](escaping-html.md) can be used for escaping HTML attributes *only* if
Chris@0: the attribute value can be **guaranteed as being properly quoted**! To avoid
Chris@0: confusion, we recommend always using the HTML Attribute escaper method when
Chris@0: dealing with HTTP attributes specifically.
Chris@0:
Chris@0: To escape data for an HTML Attribute, use `Zend\Escaper\Escaper`'s
Chris@0: `escapeHtmlAttr()` method. Internally it will convert the data to UTF-8, check
Chris@0: for its validity, and use an extended set of characters to escape that are not
Chris@0: covered by `htmlspecialchars()` to cover the cases where an attribute might be
Chris@0: unquoted or quoted illegally.
Chris@0:
Chris@0: ## Examples of Bad HTML Attribute Escaping
Chris@0:
Chris@0: An example of incorrect HTML attribute escaping:
Chris@0:
Chris@0: ```php
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0: Single Quoted Attribute
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0: ?>
Chris@0:
Chris@0: What framework are you using?
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0: ```
Chris@0:
Chris@0: In the above example, the default `ENT_COMPAT` flag is being used, which does
Chris@0: not escape single quotes, thus resulting in an alert box popping up when the
Chris@0: `onmouseover` event happens on the `span` element.
Chris@0:
Chris@0: Another example of incorrect HTML attribute escaping can happen when unquoted
Chris@0: attributes are used (which is, by the way, perfectly valid HTML5):
Chris@0:
Chris@0: ```php
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0: Quoteless Attribute
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0: ?>
Chris@0: >
Chris@0: What framework are you using?
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0: ```
Chris@0:
Chris@0: The above example shows how it is easy to break out from unquoted attributes in
Chris@0: HTML5.
Chris@0:
Chris@0: ## Example of Good HTML Attribute Escaping
Chris@0:
Chris@0: Both of the previous examples can be avoided by simply using the
Chris@0: `escapeHtmlAttr()` method:
Chris@0:
Chris@0: ```php
Chris@0:
Chris@0:
Chris@0: escapeHtmlAttr($input);
Chris@0: ?>
Chris@0:
Chris@0:
Chris@0: Quoteless Attribute
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0: ?>
Chris@0: >
Chris@0: What framework are you using?
Chris@0:
Chris@0:
Chris@0:
Chris@0:
Chris@0: ```
Chris@0:
Chris@0: In the above example, the malicious input from the attacker becomes completely
Chris@0: harmless as we used proper HTML attribute escaping!