fix php 5.6 in docker dev env (#1740)
[openemr.git] / vendor / zendframework / zend-escaper / doc / book / escaping-css.md
blob63b554bd441ce161738ec31ef56adede78a71d70
1 # Escaping Cascading Style Sheets
3 CSS is similar to [escaping Javascript](escaping-javascript.md).  CSS escaping
4 excludes only basic alphanumeric characters and escapes all other characters
5 into valid CSS hexadecimal escapes.
7 ## Example of Bad CSS Escaping
9 In most cases developers forget to escape CSS completely:
11 ```php
12 <?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); ?>
13 <!DOCTYPE html>
14 <?php
15 $input = <<<INPUT
16 body {
17     background-image: url('http://example.com/foo.jpg?</style><script>alert(1)</script>');
19 INPUT;
21 <html xmlns="http://www.w3.org/1999/xhtml">
22 <head>
23     <title>Unescaped CSS</title>
24     <meta charset="UTF-8"/>
25     <style>
26     <?= $input ?>
27     </style>
28 </head>
29 <body>
30     <p>User controlled CSS needs to be properly escaped!</p>
31 </body>
32 </html>
33 ```
35 In the above example, by failing to escape the user provided CSS, an attacker
36 can execute an XSS attack fairly easily.
38 ## Example of Good CSS Escaping
40 By using `escapeCss()` method in the CSS context, such attacks can be prevented:
42 ```php
43 <?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); ?>
44 <!DOCTYPE html>
45 <?php
46 $input = <<<INPUT
47 body {
48     background-image: url('http://example.com/foo.jpg?</style><script>alert(1)</script>');
50 INPUT;
52 $escaper = new Zend\Escaper\Escaper('utf-8');
53 $output = $escaper->escapeCss($input);
55 <html xmlns="http://www.w3.org/1999/xhtml">
56 <head>
57     <title>Escaped CSS</title>
58     <meta charset="UTF-8"/>
59     <style>
60     <?php
61     // output will look something like
62     // body\20 \7B \A \20 \20 \20 \20 background\2D image\3A \20 url\28 ...
63     echo $output;
64     ?>
65     </style>
66 </head>
67 <body>
68     <p>User controlled CSS needs to be properly escaped!</p>
69 </body>
70 </html>
71 ```
73 By properly escaping user controlled CSS, we can prevent XSS attacks in our web
74 applications.