Mercurial > hg > isophonics-drupal-site
comparison vendor/zendframework/zend-escaper/doc/book/escaping-html.md @ 0:4c8ae668cc8c
Initial import (non-working)
author | Chris Cannam |
---|---|
date | Wed, 29 Nov 2017 16:09:58 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:4c8ae668cc8c |
---|---|
1 # Escaping HTML | |
2 | |
3 Probably the most common escaping happens for **HTML body** contexts. There are | |
4 very few characters with special meaning in this context, yet it is quite common | |
5 to escape data incorrectly, namely by setting the wrong flags and character | |
6 encoding. | |
7 | |
8 For escaping data to use within an HTML body context, use | |
9 `Zend\Escaper\Escaper`'s `escapeHtml()` method. Internally it uses PHP's | |
10 `htmlspecialchars()`, correctly setting the flags and encoding for you. | |
11 | |
12 ```php | |
13 // Outputting this without escaping would be a bad idea! | |
14 $input = '<script>alert("zf2")</script>'; | |
15 | |
16 $escaper = new Zend\Escaper\Escaper('utf-8'); | |
17 | |
18 // somewhere in an HTML template | |
19 <div class="user-provided-input"> | |
20 <?= $escaper->escapeHtml($input) // all safe! ?> | |
21 </div> | |
22 ``` | |
23 | |
24 One thing a developer needs to pay special attention to is the encoding in which | |
25 the document is served to the client, as it **must be the same** as the encoding | |
26 used for escaping! | |
27 | |
28 ## Example of Bad HTML Escaping | |
29 | |
30 An example of incorrect usage: | |
31 | |
32 ```php | |
33 <?php | |
34 $input = '<script>alert("zf2")</script>'; | |
35 $escaper = new Zend\Escaper\Escaper('utf-8'); | |
36 ?> | |
37 <?php header('Content-Type: text/html; charset=ISO-8859-1'); ?> | |
38 <!DOCTYPE html> | |
39 <html> | |
40 <head> | |
41 <title>Encodings set incorrectly!</title> | |
42 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> | |
43 </head> | |
44 <body> | |
45 <?php | |
46 // Bad! The escaper's and the document's encodings are different! | |
47 echo $escaper->escapeHtml($input); | |
48 ?> | |
49 </body> | |
50 ``` | |
51 | |
52 ## Example of Good HTML Escaping | |
53 | |
54 An example of correct usage: | |
55 | |
56 ```php | |
57 <?php | |
58 $input = '<script>alert("zf2")</script>'; | |
59 $escaper = new Zend\Escaper\Escaper('utf-8'); | |
60 ?> | |
61 <?php header('Content-Type: text/html; charset=UTF-8'); ?> | |
62 <!DOCTYPE html> | |
63 <html> | |
64 <head> | |
65 <title>Encodings set correctly!</title> | |
66 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
67 </head> | |
68 <body> | |
69 <?php | |
70 // Good! The escaper's and the document's encodings are same! | |
71 echo $escaper->escapeHtml($input); | |
72 ?> | |
73 </body> | |
74 ``` |