Contextual Escaping =================== Websites and Web applications are vulnerable to XSS_ attacks, despite PHP provides escaping functionality, in some contexts those are not sufficient/appropriate. :doc:`Phalcon\\Escaper <../api/Phalcon_Escaper>` provides contextual escaping, this component is written in C providing the minimal overhead when escaping different kinds of texts. We designed this component based on the `XSS (Cross Site Scripting) Prevention Cheat Sheet`_ created by the OWASP_ Additionally, this component relies on mbstring_ to support almost any charset. To illustrate how this component works and why it is important, consider the following example: .. code-block:: html+php '; //Malicious CSS class name $className = ';`('; //Malicious CSS font name $fontName = 'Verdana"'; //Malicious Javascript text $javascriptText = "';Hello"; //Create an escaper $e = new Phalcon\Escaper(); ?> <?php echo $e->escapeHtml($maliciousTitle) ?>
hello
Which produces the following: .. figure:: ../_static/img/escape.jpeg :align: center Every text was escaped according to its context. Use the appropriate context is important to avoid XSS attacks. Escaping HTML ------------- The most common situation when inserting unsafe data is between HTML tags: .. code-block:: html
You can escape those data using the escapeHtml method: .. code-block:: html+php
escapeHtml('>

myattack

'); ?> Which produces: .. code-block:: html
></div><h1>myattack</h1>
Escaping HTML Attributes ------------------------ Escape HTML attributes is different from escape a full HTML content. The escape works by changing every non-alphanumeric character to the form. This kind of escaping is intended to most simpler attributes excluding complex ones like 'href' or 'url': .. code-block:: html
Hello
You can escape an HTML attribute by using the escapeHtmlAttr method: .. code-block:: html+php

Hello">

Hello
Which produces: .. code-block:: html
Hello
Escaping URLs ------------- Some HTML attributes like 'href' or 'url' need to be escaped differently: .. code-block:: html Some link You can escape an HTML attribute by using the escapeUrl method: .. code-block:: html+php Some link Which produces: .. code-block:: html Some link Escaping CSS ------------ CSS identifiers/values can be escaped too: .. code-block:: html Some link You can escape an HTML attribute by using the escapeCss method: .. code-block:: html+php Some link Which produces: .. code-block:: html Some link Escaping Javascript ------------------- Strings to be inserted into javascript code also must be properly escaped: .. code-block:: html You can escape an HTML attribute by using the escapeJs method: .. code-block:: html+php .. code-block:: html .. _OWASP : https://www.owasp.org .. _XSS : https://www.owasp.org/index.php/XSS .. _`XSS (Cross Site Scripting) Prevention Cheat Sheet` : https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet .. _mbstring : http://php.net/manual/en/book.mbstring.php