简体   繁体   English

PHP - 在您的代码中有多个 htmlentities()

[英]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?我刚刚遇到在PHP中构建一个CRUD应用程序,讲师提醒我们使用htmlentities()以避免HTML 注入,然后他说htmlentities不应该在您的代码中多次调用,我的问题很简单……为什么?

Cheers干杯

Because calling it a second time on the same value can double-encode it.因为在相同的值上再次调用它可以对其进行双重编码。

Taking the example from the PHP docs :PHP 文档为例:

$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:现在,如果我们再次通过htmlentities()运行它,它将对第一个htmlentities()调用创建的 & 符号进行编码,您最终将得到一个双编码字符串:

$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:关于 escaping,有两件重要的事情需要了解:

  • You should not run the same escape function twice on the same value .您不应该在相同的值上运行相同的转义 function 两次 For instance htmlentities('1 > 2') will give you 1 &gt; 2例如htmlentities('1 > 2')会给你1 &gt; 2 1 &gt; 2 , but htmlentities(htmlentities('1 > 2')) will give you 1 &amp;gt; 2 1 &gt; 2 ,但htmlentities(htmlentities('1 > 2'))会给你1 &amp;gt; 2 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.在 HTML escaping 的情况下,您应该在发送到浏览器时执行此操作,而不是在保存到数据库时或在应用程序中某处组合不同字符串时执行此操作。 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.如果你不这样做,你实际上并不知道正确的逃逸 function 使用,并且很可能最终导致数据损坏,甚至引入新的漏洞。

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.说“只在一个地方做”是记住这两件事的一种方式:如果你在 output 它的时候立即做,你就不会意外地双重转义同一个字符串,也不会应用错误的 escaping对于您将在其他地方使用的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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