I just came across building a CRUD application in PHP , and the instructor was reminding us about the use of htmlentities() in order to avoid HTML injections , and he then goes to say that htmlentities shouldnt be called more than once in your code, my question is very simple...why?
Cheers
Because calling it a second time on the same value can double-encode it.
Taking the example from the PHP docs :
$str = "A 'quote' is <b>bold</b>";
$firstEntity = htmlentities($str);
// Outputs: A 'quote' is <b>bold</b>
Now if we run that through htmlentities()
again it will encode the ampersands that the first htmlentities()
call created and you'll end up with a double-encoded string:
$secondEntity = htmlentities($firstEntity);
// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
There are two important things to know about escaping:
htmlentities('1 > 2')
will give you 1 > 2
1 > 2
, but htmlentities(htmlentities('1 > 2'))
will give you 1 &gt; 2
1 &gt; 2
. Saying "only do it one place" is a way of remembering both of these things: if you only do it immediately as you output it , you won't accidentally double-escape the same string, and you won't apply the wrong escaping for a string you're going to use somewhere else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.