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:
12 <?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); ?>
17 background-image: url('http://example.com/foo.jpg?</style><script>alert(1)</script>');
21 <html xmlns="http://www.w3.org/1999/xhtml">
23 <title>Unescaped CSS</title>
24 <meta charset="UTF-8"/>
30 <p>User controlled CSS needs to be properly escaped!</p>
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:
43 <?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); ?>
48 background-image: url('http://example.com/foo.jpg?</style><script>alert(1)</script>');
52 $escaper = new Zend\Escaper\Escaper('utf-8');
53 $output = $escaper->escapeCss($input);
55 <html xmlns="http://www.w3.org/1999/xhtml">
57 <title>Escaped CSS</title>
58 <meta charset="UTF-8"/>
61 // output will look something like
62 // body\20 \7B \A \20 \20 \20 \20 background\2D image\3A \20 url\28 ...
68 <p>User controlled CSS needs to be properly escaped!</p>
73 By properly escaping user controlled CSS, we can prevent XSS attacks in our web