简体   繁体   中英

PHP - Having more than one htmlentities() in your code

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 &lt;b&gt;bold&lt;/b&gt;

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 &amp;lt;b&amp;gt;bold&amp;lt;/b&amp;gt;

There are two important things to know about escaping:

  • You should not run the same escape function twice on the same value . For instance htmlentities('1 > 2') will give you 1 &gt; 2 1 &gt; 2 , but htmlentities(htmlentities('1 > 2')) will give you 1 &amp;gt; 2 1 &amp;gt; 2 .
  • You should only run escape functions at the point you're sending the data somewhere . In the case of HTML escaping, you should do it as you're sending to the browser , not when you save to the database, or when you're combining different strings somewhere in your application. If you don't, you don't actually know the right escape function to use, and are likely to end up with corrupted data, or even introducing new vulnerabilities.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM