$_GET 上的 foreach 循环是应用 htmlspecialchars 的好方法吗?
我想知道使用以下代码是否有一个显着的缺点:
if(isset($_GET)){
foreach($_GET as $v){
$v = htmlspecialchars($v);
}
}
我意识到可能没有必要在每个变量上使用 htmlspecialchars 。有人知道这样做是否好?
更新:
因为我认为上面的代码不起作用,所以我用我正在使用的代码更新它(尽管对建议持否定态度)。 :)
if(isset($_GET)){
foreach($_GET as $k=>$v){
$_GET[$k] = htmlspecialchars($v);
}
}
I'm wondering if there is a significant downside to using the following code:
if(isset($_GET)){
foreach($_GET as $v){
$v = htmlspecialchars($v);
}
}
I realize that it probably isn't necessary to use htmlspecialchars on each variable. Anyone know offhand if this is good to do?
UPDATE:
Because I don't think my above code would work, I'm updating this with the code that I'm using (despite the negativity towards the suggestions). :)
if(isset($_GET)){
foreach($_GET as $k=>$v){
$_GET[$k] = htmlspecialchars($v);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这完全取决于你想做什么。
一般来说,答案是“否”,您应该仅出于其预期目的专门转义数据。毫无目的地随机转义数据没有任何帮助,而且只会导致进一步的混乱,因为您必须跟踪转义的内容以及转义的方式。
简而言之,保持数据原始存储,并在使用时专门对其预期用途进行转义:
htmlentities()
。escapeshellcmd()
。urlencode()
。这个推理递归地适用。因此,如果您想编写一个指向 HTML 输出的 GET URL 的链接,它会是这样的:
如果此时您必须记住 if
$var
,那就太糟糕了之前已经逃脱了,又是如何逃脱的。This totally depends on what you want to do.
In general, the answer is "no", and you should only escape data specifically for their intended purpose. Randomly escaping data without purpose isn't helping, and it just causes further confusion, as you have to keep track of what's been escaped and how.
In short, keep your data stored raw, and escape it specifically for its intended use when you use it:
htmlentities()
.escapeshellcmd()
.escapeshellarg()
.urlencode()
on the parameter values.This reasoning applies recursively. So if you want to write a link to a GET URL to the HTML output, it'd be something like this:
It'd be terrible if at that point you'd have to remember if
$var
had already previously been escaped, and how.完全转义是没有必要的,而且可能对数据有害。不要这样做。
仅将
htmlspecialchars()
应用于要在 HTML 页面中输出的数据 - 最好是在输出之前或直接在输出时应用。Blanket escaping isn't necessary, and it's possibly harmful to the data. Don't do it.
Apply
htmlspecialchars()
only to data that you are about to output in a HTML page - ideally immediately before, or directly when you output it.它不会影响数字,但对于不打算放入 HTML 代码的字符串参数可能会适得其反。
您必须根据每个键的含义来不同地对待它。泛化的可能性还取决于您的应用程序。
It won't affect numbers, but it can backfire for string parameters which are not intended to be put in HTML code.
You have to treat each key different depending on its meaning. Possibility of generalization also depends on your application.
你这样做的方式是行不通的。您需要将
$v
设为引用,并且对于任何需要递归的内容(例如$_GET['array'][0]
),它都会中断。The way you're doing it won't work. You need to make
$v
a reference, and it breaks for anything requiring recursion ($_GET['array'][0]
, for example).