Chris@0: # Escaping HTML Chris@0: Chris@0: Probably the most common escaping happens for **HTML body** contexts. There are Chris@0: very few characters with special meaning in this context, yet it is quite common Chris@0: to escape data incorrectly, namely by setting the wrong flags and character Chris@0: encoding. Chris@0: Chris@0: For escaping data to use within an HTML body context, use Chris@0: `Zend\Escaper\Escaper`'s `escapeHtml()` method. Internally it uses PHP's Chris@0: `htmlspecialchars()`, correctly setting the flags and encoding for you. Chris@0: Chris@0: ```php Chris@0: // Outputting this without escaping would be a bad idea! Chris@0: $input = ''; Chris@0: Chris@0: $escaper = new Zend\Escaper\Escaper('utf-8'); Chris@0: Chris@0: // somewhere in an HTML template Chris@0:
Chris@0: escapeHtml($input) // all safe! ?> Chris@0:
Chris@0: ``` Chris@0: Chris@0: One thing a developer needs to pay special attention to is the encoding in which Chris@0: the document is served to the client, as it **must be the same** as the encoding Chris@0: used for escaping! Chris@0: Chris@0: ## Example of Bad HTML Escaping Chris@0: Chris@0: An example of incorrect usage: Chris@0: Chris@0: ```php Chris@0: alert("zf2")'; Chris@0: $escaper = new Zend\Escaper\Escaper('utf-8'); Chris@0: ?> Chris@0: Chris@0: Chris@0: Chris@0: Chris@0: Encodings set incorrectly! Chris@0: Chris@0: Chris@0: Chris@0: escapeHtml($input); Chris@0: ?> Chris@0: Chris@0: ``` Chris@0: Chris@0: ## Example of Good HTML Escaping Chris@0: Chris@0: An example of correct usage: Chris@0: Chris@0: ```php Chris@0: alert("zf2")'; Chris@0: $escaper = new Zend\Escaper\Escaper('utf-8'); Chris@0: ?> Chris@0: Chris@0: Chris@0: Chris@0: Chris@0: Encodings set correctly! Chris@0: Chris@0: Chris@0: Chris@0: escapeHtml($input); Chris@0: ?> Chris@0: Chris@0: ```