[英]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 <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:现在,如果我们再次通过
htmlentities()
运行它,它将对第一个htmlentities()
调用创建的 & 符号进行编码,您最终将得到一个双编码字符串:
$secondEntity = htmlentities($firstEntity);
// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
There are two important things to know about escaping:关于 escaping,有两件重要的事情需要了解:
htmlentities('1 > 2')
will give you 1 > 2
htmlentities('1 > 2')
会给你1 > 2
1 > 2
, but htmlentities(htmlentities('1 > 2'))
will give you 1 &gt; 2
1 > 2
,但htmlentities(htmlentities('1 > 2'))
会给你1 &gt; 2
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.说“只在一个地方做”是记住这两件事的一种方式:如果你只在 output 它的时候立即做,你就不会意外地双重转义同一个字符串,也不会应用错误的 escaping对于您将在其他地方使用的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.